最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

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 | }
Share Improve this question edited Sep 10, 2022 at 16:13 ikos23 5,38212 gold badges45 silver badges64 bronze badges asked Sep 10, 2022 at 16:05 voyt97voyt97 2464 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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)
  )
发布评论

评论列表(0)

  1. 暂无评论