[SOLVED] NextJS: how to call function from within JSX to close modal


This Content is from Stack Overflow. Question asked by FlameDra

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'


        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>) => {


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 (
            <Modal open={props.open}>
                <Modal.Header>Add Trip</Modal.Header>
                <label onClick={props.onClose}>
                        <form onSubmit={handleSubmit}>
                            <...form fields...>
                                    {isLoading ? (
                                    ) : (
                                            {isError ? (
                                                    An error occurred:
                                                    {error instanceof Error ? error.message : 'Unknown error!'}
                                            ) : null}

                                            {isSuccess ? props.onClose : null}


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

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?


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) => {
const { mutate, isSuccess, isLoading, isError, error } = useMutation(addDay,{onSuccess})

doc reference: https://tanstack.com/query/v4/docs/reference/useMutation

This Question was asked in StackOverflow by FlameDra and Answered by Shubham Verma It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?