Pedro135
Pedro135

Reputation: 33

React Query On Success does not trigger

I'm currently having a problem that I can't explain. I work with React, typescript and react query. The code on which I work is a double modal and when clicking on the refuse button of the second one launches a call via react query then we execute an onSuccess.

If I move the hook call into the first modal the onSuccess fires. If I move the OnSuccess from the second modal into the hook it works too.

But I don't understand why in this case it doesn't work... Does anyone have an idea/explanation please?

Thanks in advance.

Here is the code below of the first modal

import React from 'react'
import Button from '../Button'
import SecondModal from '../SecondModal'

interface FirstModalProps {
    isOpen: boolean
    setIsOpen: React.Dispatch<React.SetStateAction<boolean>>
    id?: string
}

const FirstModal = ({ id, isOpen, setIsOpen }: 
FirstModalProps) => {
    const [openRefuse, setOpenRefuse] = React.useState<boolean>(false)

return (
    <>
        <SecondModal isOpen={openRefuse} setIsOpen={setOpenRefuse} id={id} />
        <Button
            onClick={() => {
                setIsOpen(false)
                setOpenRefuse(true)
            }}
            text="refuse"
        />
    </>
)}

export default FirstModal

Then the code of the second modal

import React from 'react'
import ConfirmModal from '../../../../../shared/styles/modal/confirm'
import useUpdate from '../../hooks/use-update'

interface SecondModalProps {
    isOpen: boolean
    setIsOpen: React.Dispatch<React.SetStateAction<boolean>>
    id?: string
}

const SecondModal = ({ isOpen, setIsOpen, id }: SecondModalProps) => {
const { mutate: update } = useUpdate()

const updateT = () => {
    update(
        {
            id
        },
        {
            onSuccess: () => {
                console.log('OnSuccess trigger')
            }
        }
    )
}

return (
    <ConfirmModal
        close={() => {
            setIsOpen(false)
        }}
        isOpen={isOpen}
        validate={updateT}
    />
)}

export default SecondModal

Then the hook

import { useMutation } from 'react-query'

interface hookProps {
    id?: string
}

const useUpdate = () => {
const query = async ({ id }: hookProps) => {
    if (!id) return
    return (await myApi.updateTr(id))()
}

return useMutation(query, {
    onError: () => {
        console.log('error')
    }
})}

export default useUpdate

Upvotes: 1

Views: 7436

Answers (1)

TkDodo
TkDodo

Reputation: 28733

callbacks passed to the .mutate function only execute if the component is still mounted when the request completes. On the contrary, callbacks on useMutation are always executed. This is documented here, and I've also written about it in my blog here.

Upvotes: 3

Related Questions