voyt97
voyt97

Reputation: 236

Can't pass any arguments to mutate function in react-query with typescript

I'm trying to use react-query and axios to send post request to backend to register an user but when I try to trigger mutation with arguments by clicking on the button I'm getting an error.

import React from 'react'
import { useMutation } from '@tanstack/react-query'
import axios from 'axios'
import { Button } from 'react-bootstrap'

const RegisterScreen = () => {
  const { data, error, isLoading, mutate } = useMutation((user) =>
    axios.post('/api/users', user)
  )

  const user = { name: 'john', email: '[email protected]', password: '1234' }

  return (
    <div>
      <Button onClick={() => mutate(user)}>Register</Button>
    </div>
  )
}

export default RegisterScreen

Error message:

ERROR in src/screens/RegisterScreen.tsx:15:37
[1] TS2345: Argument of type '{ name: string; email: string; password: string; }' is not assignable to parameter of type 'void'.
[1]     13 |   return (
[1]     14 |     <div>
[1]   > 15 |       <Button onClick={() => mutate(user)}>Register</Button>
[1]        |                                     ^^^^
[1]     16 |     </div>
[1]     17 |   )
[1]     18 | }

Upvotes: 4

Views: 3700

Answers (1)

voyt97
voyt97

Reputation: 236

Solved: i had to add type to user argument in mutate function:

const { data, error, isLoading, mutate } = useMutation(
    (user: { name: string; email: string; password: string }) =>
      axios.post('/api/users', user)
  )

Upvotes: 7

Related Questions