skip to Main Content

I am fetching data from a graphql API, and after fetching the data once, I want it to persist on page reloads, and it should only make a new API call when the query changes. I’m using @apollo/client to fetch the data from an API.

My code:

import { useQuery } from "@apollo/client";
import { useSearchParams } from "react-router-dom";

const Component = () => {
  const { loading, error, data } = useQuery(queryGql, {
    variables: queryVariables,
  });

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }
  const results = data?.data || [];

  return (
      <div>
        {results.map((result) => (
          <Card name={result.name} key={result.id} />
        ))}
      </div>
  );
};

export default Component;

index.js

import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";

const client = new ApolloClient({
  uri: process.env.BASE_URL,
  cache: new InMemoryCache(),
});

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <RouterProvider router={router} />
    </ApolloProvider>
  </React.StrictMode>
);

2

Answers


  1. you can use Redux to do this.

    https://redux.js.org/

    And use Redux persist for persist the data, even when the page is reloaded

    https://github.com/rt2zz/redux-persist

    And then, you can make a condition in your code, to avoid rerunning the query if you already have the data.

    Login or Signup to reply.
  2. Almost all of this answer comes from queries#setting-a-fetch-policy

    In @apollo/client, You can specify a different fetch policy for a given query. To do so, include the fetchPolicy option in your call to useQuery:

    const { loading, error, data } = useQuery(queryGql, {
      fetchPolicy: 'cache-first', // first executes the query against the cache.
    });
    

    Apollo Client first executes the query against the cache. If all requested data is present in the cache, that data is returned. Otherwise, Apollo Client executes the query against your GraphQL server and returns that data after caching it.

    Prioritizes minimizing the number of network requests sent by your application.

    @apollo/client supports the following configurations:

    • cache-first
    • cache-only
    • cache-and-network
    • network-only
    • no-cache
    • standby

    In my opinion, you should choose cache-first, and it’s the default fetch policy.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search