Artur Subotkevič
Artur Subotkevič

Reputation: 1939

Apollo React - `useMutation` in ApolloClient setup?

I have an interesting situation.

I want to initiate refresh token request USING Apollo itself (a.k.a to call a mutation)

Any idea, how to achieve something like this?

export default new ApolloClient({
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError, operation, forward }) => {
      // useMutation(REFRESH_ACCESS_TOKEN)
    }),
  ]),

  new HttpLink({...}),
})

Basically I'm just trying to useMutation(REFRESH_ACCESS_TOKEN) inside onError while creating new ApolloClient instance.

The problem: Invalid hook call. Hooks can only be called inside of the body of a function component.

Thanks.

Upvotes: 0

Views: 929

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

You can't use a hook outside a functional React component. You can use the client directly to make queries and mutations -- just bear in mind that any queries ran this way will not be observable (i.e. won't be updated if the cache changes).

const client = new ApolloClient({
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError, operation, forward }) => {
      client.mutate({ mutation, variables })
        .then(({ data }) => {
          console.log(data)
        })
        .catch((error) => {
          console.log(error)
        })
    }),
    new HttpLink({...}),
  ]),
})

export default client

Upvotes: 2

Related Questions