Putxe
Putxe

Reputation: 1074

How to refresh variables in react-apollo

Here is the scenario :

USER 1

Here is the query :

const PROFILE_QUERY = gql`
  query profileQuery($id: ID!) {
    getUser(id: $id) {
      firstName
      lastName
      email
    }
  }
`;

export default graphql(PROFILE_QUERY, {
  options: {
    variables: {
      id: localStorage.getItem("id")
    },
    errorPolicy: "all"
  }
})(ProfilePage);

So everything is working for the first user, now a second user arrives at the same computer and the same browser.

USER 2

If I do a browser refresh the query is sent with the good user id...

So why the id variable is not refreshed (seems like the id value in local storage is not read) at the first attempt ? How can I resolve this ?

Thank you for your help.

Upvotes: 0

Views: 1179

Answers (2)

Tal Z
Tal Z

Reputation: 3210

That happens because your options field is static and is evaluated when the file containing the query is first loaded. (I'm assuming somewhere, perhaps steps 3 or 4, the id in local storage is updated correctly for the second user.)

config.options can be an object like the one you are passing now or a function that is evaluated when needed by the query.

So to load the id from the localStorage each time instead of just once, you can do something like this:

options: () => ({
  variables: {
    id: localStorage.getItem("id")
  },
  errorPolicy: "all"
})

Upvotes: 3

none
none

Reputation: 1817

Then first user logged out, you need to reset Apollo store and clear local storage.

Upvotes: 0

Related Questions