Home > front end >  How to store data from GraphQL response in sessionStorage?
How to store data from GraphQL response in sessionStorage?

Time:10-12

I'm trying to save my GraphQL response in sessionStorage, so I get access to it in several places and I don't need to make an API call more then once. The problem is, I'm not sure how am I supposed to do this. I'm trying to use useQuery hook with skip property where I check if sessionStorage.getItem("ITEM") exists or not, if not - set it, then check again. I think it's not the best practice and I'm pretty sure that there is something better I could do.

Here's the hook which I'm trying to make as reusable, to check if sessionStorage exists and optionally save it.

export const useGetClientQuery = () => {
  let { data: clientList, loading } = useQuery<any>(getClientsQuery(), {
    client: ApiClient.configGraphqlClient,
    skip: sessionStorage.getItem("clientsList") ? true : false,
  });

  if (clientList) sessionStorage.setItem("clientsList", JSON.stringify(clientList));

  const clientListJSON = sessionStorage.getItem("clientsList");

  return { clientListJSON };
};

and this is an example how I'm trying to use it:

  const { clientListJSON } = useGetClientQuery();

  const clientList = JSON.parse(clientListJSON); // I'm working with typescript, which shows an error: Argument of type 
'string | null' is not assignable to parameter of 
type 'string'.
  Type 'null' is not assignable to type 'string'.

and I know why this is happening but I don't really know how to do it differently. Looking for some good advices :)

CodePudding user response:

so I get access to it in several places

Just use the state provided by the query result in every component that needs it1 2 3.

and I don't need to make an API call more then once

The useQuery hook supports a staleTime option that — if set to Infinity — configures the value to be cached for the lifetime of the JS execution context (session): so subsequent invocations will just return the cached value instead of re-fetching.

Check out the documentation!


1 React docs - Lifting State Up

2 React docs beta - Sharing State Between Components

3 React docs beta - Passing Data Deeply with Context

CodePudding user response:

useQuery is meant to be used as a hook in a react component. You should see that loading is true for awhile until data is returned.

Try using await client.query() where client is your ApolloClient object.

You might find local storage even more useful than session storage since it also survives a page refresh which neither session nor a prop at a higher level would.

  • Related