0

Here is the scenario :

USER 1

  • 1) Goes to login page
  • 2) Writes email and password which are sent to the server by a mutation
  • 3) Authentication OK -> the server returns a token and user informations (id, firstName, lastName)
  • 4)The token and each user information are stored in a separate key in local storage
  • 5) The user is redirected to the HomePage
  • 6) The user goes to Profile Page
  • 7) A query is sent to the server to retrieve all the informations about that user (thanks to the user id stored in local storage)

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);
  • 8) The server returns the informations and the user can see them in the Profile Page
  • 9) The user decides to logout

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

USER 2

  • Same steps than the previous user from 1 to 7
  • The query sent to the server to retrieve user informations is not working because the id sent by the query is the id of the previous user (and a user is not allowed to retrieve informations about an other user)

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.

2 Answers 2

3

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"
})
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is perfect I didn't know about that ! Thanks a lot Tal Z my query is now running perfectly !
0

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

1 Comment

Thank you for your answer none, I have not mentioned that but I reset already the Apollo store with "this.props.client.resetStore" and I remove the items from local storage

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.