Apollo React - `useMutation` in ApolloClient setup?

给你一囗甜甜゛ 提交于 2021-02-17 06:12:14

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/60028883/apollo-react-usemutation-in-apolloclient-setup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!