Lin Du
Lin Du

Reputation: 102287

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.

Upvotes: 5

Views: 3190

Answers (2)

Noby Fujioka
Noby Fujioka

Reputation: 1824

Mikael's answer works for me. Just use client.resetStore(); in onError like Mikael's answer.

But, also make sure to link errorLink to client as an example below:

const client = new ApolloClient({
  cache,
  link: authLink.concat(errorLink).concat(restLink).concat(httpLink),
  resolvers
});

Upvotes: 0

Mikael Lirbank
Mikael Lirbank

Reputation: 4615

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,
  ]),
});

Upvotes: 2

Related Questions