I'm using the Tanstack React Query library to do a POST from a Modal which contains a form:
const addDay = (day: TDay) => {
const apiURL = process.env.NEXT_PUBLIC_SERVER_URL
const queryURL = apiURL router.asPath '/days'
console.log(queryURL)
return axios.post<TDay>(queryURL, day, {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
Accept: 'application/json',
},
})
}
const { mutate, isSuccess, isLoading, isError, error } = useMutation(addDay)
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
mutate(day)
}
In my return JSX, I would like to close the Modal when I click Submit and it isSuccess
. I'm trying to do it as:
return (
<div>
<Modal open={props.open}>
<Modal.Header>Add Trip</Modal.Header>
<label onClick={props.onClose}>
✕
</label>
<Modal.Body>
<div>
<form onSubmit={handleSubmit}>
<...form fields...>
<Modal.Actions>
<div>
{isLoading ? (
<Button>Adding</Button>
) : (
<>
{isError ? (
<h2>
An error occurred:
{error instanceof Error ? error.message : 'Unknown error!'}
</h2>
) : null}
{isSuccess ? props.onClose : null}
<Button>Submit</Button>
</>
)}
</div>
</Modal.Actions>
</form>
</div>
</Modal.Body>
</Modal>
</div>
)
The main issue is in the {isSuccess ? props.onClose : null}
where even if isSuccess
is true, it's not calling props.onClose and closing the modal.
I know props.onClose works because I have an X button defined above as:
<label onClick={props.onClose}>
✕
</label>
And when I click it, it does close the modal.
How can I also call this function from within JSX so I can close the Modal when isSuccess
is true?
CodePudding user response:
The better way would be call on onSuccess
.
According to there doc you can pass onSuccess
function.
You can do something like this:
const onSuccess = (data) => {
props.onClose()
}
const { mutate, isSuccess, isLoading, isError, error } = useMutation(addDay,{onSuccess})
doc reference: https://tanstack.com/query/v4/docs/reference/useMutation