Calling a hook (useMutation) inside an event handler error: “Hooks can only be called inside of the body of a function component”

佐手、 提交于 2019-12-25 03:50:32

问题


I want to use a mutation in an event handler. My event is defined like so:

(JSX attribute) onOk?: ((e: React.MouseEvent<any, MouseEvent>) => void) | undefined

This is how I call the mutation from the client

export const IMPORT_INFO_MUTATION = gql`
  mutation ImportPolicy($data: ImportPolicyInput!) {
    importPolicy(data:$data)
    {
      _id
      name
    }
 }

And eventually I call it like so:

      onOk={() => {

        useImportPolicyMutation({
          variables: {
            data: {
              jsonData: JSON.parse(importPolicyData)
            }
          },
        })
      }

`Don't worry about the variables and params in the mutation. They are fine. The issue is that I get the following error:

Unhandled Rejection (Invariant Violation): Invalid hook call. Hooks can only 
be called inside of the body of a function component. This could happen for 
one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)

2. You might be breaking the Rules of Hooks

3. You might have more than one copy of React in the same app

It is a hook because the useMutation is defined like so:

  return ReactApolloHooks.useMutation<ImportPolicyMutation, ImportPolicyMutationVariables>(
   ImportPolicyDocument,
baseOptions
 )

So, how do I call a mutation inside an event handler?


回答1:


So, how do I call a mutation inside an event handler?

  1. Hooks are ONLY for functional components, not for class based (use apollo client.mutation() or <Mutation/> component)
  2. useMutation returns function intended to be used on demand - this function must be used in event handler, not entire useMutation

react-apollo-hooks project description contains an example of usemutation used with event handler.



来源:https://stackoverflow.com/questions/56212612/calling-a-hook-usemutation-inside-an-event-handler-error-hooks-can-only-be-c

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