1

I am trying to implement Gatsby with Apollo Client

Here is my gatsby-browser.js file

export const wrapPageElement = ({ element, props }) => {
  const client = new ApolloClient({
    uri: "http://localhost:3000/graphql",
    cache: new InMemoryCache(),
    credentials: "include",
  });
  window.a = client;
  return (
    <CookiesProvider>
      <ApolloProvider client={client}>
        <ChakraProvider theme={theme} {...props}>
          {element}
        </ChakraProvider>
      </ApolloProvider>
    </CookiesProvider>
  );
};

I am persisting my logged in user details in GraphQL cache so that it can be accessed anywhere in my application. Here is the code of logging in

 const [login, { data, error }] = useMutation(AUTH_USER, {
    onCompleted: ({ login: data }) => {
      try {
        client.writeFragment({
          id: "me",
          fragment: FRAGMENTS_USER.all_details,
          data: data,
        });
        setToken(data.token);
      } catch (e) {}
    },
  });

My problem is that the cache is being reset on navigation. So, using gatsby-link or gatsby-navigation is resetting my cache

I have been using NextJS, and it is the first time I am writing applications in Gatsby, but it doesn't seem to behave like a Single-Page application in that case.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67

1 Answers1

0

wrapPageElement and wrapRootElement APIs need to be used across gatsby-browser.js and gatsby-ssr.js. Both files need to share the same content to avoid persistence errors. So, in your gatsby-ssr.js:

export const wrapPageElement = ({ element, props }) => {
  const client = new ApolloClient({
    uri: "http://localhost:3000/graphql",
    cache: new InMemoryCache(),
    credentials: "include",
  });
  window.a = client;
  return (
    <CookiesProvider>
      <ApolloProvider client={client}>
        <ChakraProvider theme={theme} {...props}>
          {element}
        </ChakraProvider>
      </ApolloProvider>
    </CookiesProvider>
  );
};

As you can see in Gatsby's docs:

Note: There is an equivalent hook in Gatsby’s Browser API. It is recommended to use both APIs together. For example usage, check out Using redux.

Maybe this fixes your issue.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67