简体   繁体   English

react-query中如何使用useMutation的响应来显示数据?

[英]How to use the response of useMutation in react-query to display data?

I am using react-query's useMutation() to POST data, I am able to successfully post the data.我正在使用 react-query 的 useMutation() 来发布数据,我能够成功发布数据。 But, The response i am returning after successfully posting the data I want to use that response and display it in component但是,我在成功发布我想要使用该响应并将其显示在组件中的数据后返回的响应

For this I am using state, and i am setting state inside onSuccess function in useMutation() hook, but it is giving me error Error: TypeError: Cannot read property 'tidpWarnings' of undefined at Object.onSuccess (UpdateMIDPPage.jsx:80) at mutation.js:86 For this I am using state, and i am setting state inside onSuccess function in useMutation() hook, but it is giving me error Error: TypeError: Cannot read property 'tidpWarnings' of undefined at Object.onSuccess (UpdateMIDPPage.jsx:80)在突变.js:86

Below is my code for reference下面是我的代码供参考

const UpdateMIDPPage = ({ open, handleClose }) => {
  const classes = useStyles()
  const [tidpFiles, setTidpFiles] = useState([])
  const [reportFile, setReportFile] = useState('')
  const [tidpWarnings, setTidpWarnings] = useState([])
  const [reportWarnings, setReportWarnings] = useState([])
  const [toggleVisibleIcon, setToggleVisibleIcon] = useState(true)

  const { mutate, data, isSuccess, isLoading, isIdle, isError } = useMutation(
    async (body) => {
      const resp = await axios.post('http://localhost:4000/api/v1/midp/update', body)
      return resp.data
    },
    {
      onSuccess: async (data) => {    
        console.log(data)
        setTidpWarnings(data.warnings1.tidpWarnings)
        setReportWarnings(data.warnings1.reportWarnings)
      },
      onError: async (error) => {
        console.log(error)
      },
    },
  )
  const handleUpdateMIDP = () => {
    const body = {
      projectId,
      tidpFiles,
      reportFile,
    }
    mutate(body)
    // also tried this doesnt work eiter
    // mutate(body, {
    //   onSuccess: async () => {
    //     setTidpWarnings(data.warnings1.tidpWarnings)
    //     setReportWarnings(data.warnings1.reportWarnings)
    //   },
    // })
  }

  return (
    <div className={classes.container}>
      <div className={classes.action}>
        <div>       
          <Button
            onClick={handleUpdateMIDP}
            className={classes.updateBtn}
            variant='contained'
            disableElevation
            startIcon={<CheckIcon />}
            disabled={tidpFiles === [] ? true : reportFile === '' ? true : isSuccess ? true : false}
          >
            {isIdle
              ? 'Generate MIDP'
              : isLoading
              ? 'Processing...'
              : isSuccess
              ? 'Processed!'
              : isError
              ? 'Error'
              : null}
          </Button>
        </div>
        <div>         
          <Tooltip title='Toggle upload section'>
            <IconButton onClick={() => setToggleVisibleIcon(!toggleVisibleIcon)}>
              {toggleVisibleIcon ? <VisibilityIcon /> : <VisibilityOffIcon />}
            </IconButton>
          </Tooltip>
        </div>
      </div>
      {toggleVisibleIcon ? (
        <UploadSection
          reportFile={reportFile}
          setReportFile={setReportFile}
          tidpFiles={tidpFiles}
          setTidpFiles={setTidpFiles}
        />
      ) : null}
      {isLoading ? <div>loading ....</div> : null}
      {isSuccess ? <WarningSection tidpWarnings={tidpWarnings} reportWarnings={reportWarnings} /> : null}
    </div>
  )
}

If i comment the setState code inside the onSuccess, everything works fine.如果我在 onSuccess 中注释 setState 代码,一切正常。

Here is the APi response for reference这是 APi 响应供参考

{status: "success", data: {…}}
data:
ignoreFiles: (2) ["test1.xlsx", "test5.xlsx"]
warnings1: {tidpWarnings: Array(3), reportWarnings: Array(0)}
__proto__: Object
status: "success"
__proto__: Object

Please help me in figuring this out, thx请帮我解决这个问题,谢谢

For this I am using state, and i am setting state inside onSuccess function in useMutation() hook为此,我使用 state,并且我在 useMutation() 钩子中的 onSuccess function 中设置 state

The data returned from useMutation will contain the response returned from the api, so there shouldn't be the need to add extra state management从 useMutation 返回的data将包含从 api 返回的响应,因此不需要添加额外的 state 管理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM