首页 > 解决方案 > 根据条件响应 Apollo Query

问题描述

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

1)如果应用程序是online,从服务器获取详细信息。

2)如果应用程序是offline,从本地存储中获取详细信息。

我可以让每个条件自己工作。但是(我对 react 和 apollo-react 还很陌生),我不确定如何向查询添加条件。

下面是我从服务器获取数据的查询示例(我有这部分工作)

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 钩子。

标签: reactjsionic-frameworkreact-apollo

解决方案


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>
    );
  }
}

推荐阅读