Categories
React Answers

How to reset store after logout with Apollo client and React?

Spread the love

To reset store after logout with Apollo client and React, we set the Mutation component’s onCompleted prop to a function that clears the store.

For instance, we write

<Mutation
  mutation={LOGOUT_MUTATION}
  onCompleted={() => {
    sessionStorage.clear();
    client.clearStore().then(() => {
      client.resetStore();
      history.push("/login");
    });
  }}
>
  {(logout) => (
    <button
      onClick={() => {
        logout();
      }}
    >
      Logout <span>{user.userName}</span>
    </button>
  )}
</Mutation>;

to set onCompleted to a function that clears sessionStorage with

sessionStorage.clear();

Then we clear the Apollo store with

client.clearStore().then(() => {
  client.resetStore();
});

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *