Ad

React Apollo Query Based On A Condition

- 1 answer

I'm currently building an app (hybrid mobile app) to show a list of records (places). Following is my requirement,

1) If the app is online, get the details from the server.

2) If the app is offline, get the details from the local storage.

I can get each condition working by its own. However (I'm fairly new to react and apollo-react), I'm not sure how to add a condition to the query.

below is an example of my query on getting the data from the server (I have this part working)

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

pseudocode for this I'm thinking would be,

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

Can anyone point me in the correct direction. TIA.

Also, I'm using a latest version of react and I have the flexibility of using react hooks if that required.

Ad

Answer

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>
    );
  }
}
Ad
source: stackoverflow.com
Ad