问题
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?
- Hooks are ONLY for functional components, not for class based (use apollo
client.mutation()
or<Mutation/>
component) useMutation
returns function intended to be used on demand - this function must be used in event handler, not entireuseMutation
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