1
votes

I'm having some troubles with Apollo client and was wondering if someone could help me out here.

How can I re-run my query (with headers) after a succesful mutation which returns me a bearer token?

I found out there is something called refetchQueries, but it seems to ignore all the headers thus my bearer token as well.

Say I have the following mutation in my Login component:

<Mutation
  mutation={LOGIN_USER}
  refetchQueries={[{
    query: GET_USER,
  }]}
>
  {(loginUser, { loading, error, data }) => {
    if (data) {
      cookies.set('token', data.loginUser.token)
    }
    return (
      <form...

and the following authLink in my App.js:

const authLink = setContext((_, { headers }) => {
  const token = cookies.get('token')

  return {
    headers: {
      ...headers,
      authorization: token  ? `Bearer ${token}`  : null
    },
  }
})

Problem seems to be that the authLink thingy doesn't work when using refetchQueries (no headers are sent). When I refresh the browser my query works ok as the cookie is then used to get the token, but this doesn't seem to happen with refetchQueries...

So how could I run my query after the mutation with the bearer token in the header or is there a better way to do this?

Cheers

1
Did you managed to solve this? I'm currently having the exact same problem.Darryl Young

1 Answers

1
votes

I don't know how you define your queries and mutations, but refetchQueries can take an array of strings naming the queries to be refetched. I found this to suit my needs. To accomplish this, you need to name your queries. Inside the gql tag, declare your query like

const GET_USER = gql`
query getUser($id: ID) {
  user(id: $id) {
    name
  }
}
`

Then you call refetchQueries with just ['getUser']

About setting up Apollo to automatically set the authorisation headers on every request, just look at the examples from the docs

Scroll down to the section about middleware