4

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 | }

1 Answer 1

7

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)
  )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.