根据条件反应Apollo查询

时间:2019-09-02 08:03:02

标签: reactjs ionic-framework react-apollo

我当前正在构建一个应用程序(混合移动应用程序)以显示记录列表(位置)。以下是我的要求,

1)如果应用为online,请从服务器获取详细信息。

2)如果应用为offline,请从本地存储获取详细信息。

我可以使每个条件独立运行。但是(我对反应和阿波罗反应还很陌生),我不确定如何向查询中添加条件。

下面是我从服务器获取数据的查询示例(我正在处理此部分)

const client = new ApolloCient({
  uri: "/graphql"
});

const PLACES_LIST = gql`
  {
    places {
      id
      title
    }
  }
`;

class PlacesList extends React.Component {
  render() {
    return (
      <ApolloProvider client={client}>
        <Query query={PLACES_LIST}>
          {({ loading, data }) => {
            if (loading) return "Loading....";
            const { places } = data;
            return places.map(place => (
              <PlaceDetail
                key={place.id}
                place={place}
              ></PlaceDetail>
            ));
          }}
        </Query>
      </ApolloProvider>
    );
  }
}

我想是的伪代码

if (online) {
  # run apollo client
} else {
  # read from the local storage
}

谁能指出我正确的方向。 TIA。

此外,我正在使用最新版本的react,并且可以根据需要灵活地使用react钩子。

2 个答案:

答案 0 :(得分:1)

const client = new ApolloCient({
  uri: "/graphql"
});

const PLACES_LIST = gql`
  {
    places {
      id
      title
    }
  }
`;

class PlacesList extends React.Component {
  render() {
    return (
      <ApolloProvider client={client}>
        <Query query={PLACES_LIST}>
          {({ loading, data, error }) => {
            // There is also an error parameter from the hook
            if (loading) return "Loading....";
            // Here You can decide if its a connection error or smt other. 
            // I would recoment the fetchPolicy="network-only" prop for your <Query> in this case
            if(error) {
              return localstorage.getItem("Smt");
            } else {
              const { places } = data;
              return places.map(place => (
                <PlaceDetail
                  key={place.id}
                  place={place}
                ></PlaceDetail>
              ));
            }
          }}
        </Query>
      </ApolloProvider>
    );
  }
}

答案 1 :(得分:1)

也许您可以尝试使用the navigator interface检查网络连接。我不确定navigator.onLine是否在混合移动应用程序中可用,但是很容易检查。 您可以执行以下操作:

render(){
 const isOnline = navigator.onLine
 return (
    <div>
      {isOnline ? (
        <ApolloProvider client={client}></ApolloProvider>
      ) : (
        <LocalStorageComponent />
      )}
    </div>
  );
}