Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access apollo client in apollo-link-error to resetStore?

I am building an authentication system based on JWT.

JWT has expired time. When JWT expires, I catch JWT expired error using apollo-link-error. I want to invoke apolloClient.resetStore() method to reset the cache.

Here is my code:

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(error => {
      // console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
      if (error.code === 1001) {
        auth.signout();

        // how can I get apollo client here?
        //client.resetStore();
      }
    });
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const client = new ApolloClient({
  cache,
  link: from([authMiddleware, errorLink, terminalLink])
});

I am not sure apollo-link-error is the right place to handle the error of expired JWT.

like image 768
slideshowp2 Avatar asked Nov 08 '22 03:11

slideshowp2


1 Answers

You should simply be able to call the client directly:

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    client.resetStore();
  }
});

const client = new ApolloClient({
  cache: new InMemoryCache({ fragmentMatcher }),
  link: ApolloLink.from([
    errorLink,
    // otherLink,
    // otherLink,
  ]),
});

You can even call it from a nested configuration function:

const client = new ApolloClient({
  cache: new InMemoryCache({ fragmentMatcher }),
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors) {
        client.resetStore();
      }
    }),
    // otherLink,
    // otherLink,
  ]),
});
like image 76
Mikael Lirbank Avatar answered Dec 11 '22 22:12

Mikael Lirbank