How to Use Multiple Parameters in useMutation From React Query With TypeScript

Tobias Daffner
The Startup
Published in
2 min readOct 25, 2020
Coding
Photo by Ilya Pavlov on Unsplash

I’m really like React Query. For me, it makes backend communication with my React application much easier and let me abandon Redux or the Context API to manage data from the backend in my fronded.

Get data from your backend with useQuery was quite straightforward for me, however, useMutation introduced some sort of complexity.

Let’s say I have a function to update a journal entry for one user in my backend.

The updateJournalEntryforUser function takes an updated journal entry, the id of the journal entry to be updated and the user id to which the entry belongs.

However, now using this function with the useMutate hook results in type errors.

The reason for this is, that the MutationFunction takes only one parameter called variables. However, this can be an object and properties can be deconstructed in our updateJournalEntryForUser function.

Since we write this in TypeScript, we also need to add an interface for the parameters, we want to deconstruct from our variables object.

We also need to do changes when calling our mutation function, as we are now passing an object instead of three individual parameters.

That’s it. We can now use our function with multiple parameters combined in one object and correctly typed.

Hopefully, this quick summary will help you to use useMutation in React Query more often in your application.

Keep on coding!

--

--

Tobias Daffner
The Startup

I’m a self-taught web developer who loves React, the Jamstack and serverless architectures. Lives and works in Munich. Opinions are my own.