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
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.
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 touseQuery
:@apollo/client supports the following configurations:
In my opinion, you should choose
cache-first
, and it’s the default fetch policy.