Search code examples
reactjstypescriptgraphqlgraphql-mutation

Can I make multiple useMutation in a components


I have a question about using multiple mutation in a component.

For example, if I need to create and update the same component, how can I make them?

When I make like

const [createUser, {data}] = useMtation(CREATE_USER, {user}) - create user

const [updateUser, {data}] = useMtation(UPDATE_USER, {user}) - update user

Using those, I want to do like this -

If I click create, the first one is gonna work,

When I click the edit button, the button will show the update user and will work the second one.

Then, I have an error because I have two data.

Can I have some good examples for my question?


Solution

  • To resolve your error, you can rename the variable you are destructuring. As mentioned in the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment under the "Assigning to new variable names" section, you can do the following:

    const [createUser, {data: createUserData}] = useMutation(CREATE_USER, {user}) // create user
    
    const [updateUser, {data: updateUserData}] = useMutation(UPDATE_USER, {user}) // update user
    

    To add a comment on the design of you component, it is not React good practice to bundle together distinct logic like create & update in the same component.

    What you should ideally do is, have a separate component for your Create button where you have the only create mutation & a separate component for your Update button where you have the only the update mutation.