简体   繁体   中英

How to trigger popup notification on submit of a form in React using React Router navigate hook?

I'm trying to trigger a pop-up notification success message on submission of a form in React. The issue is that on submit, the page redirects to a separate page using React Router's useNavigate() hook and there's no relationship between the form component and the redirected page, so I need some way to trigger the pop-up after the redirection has taken place.

Currently I am using useNavigate's state prop to pass a true boolean value to the redirected page on submission of the form. This works by using a useEffect hook to checking first if the value is true when the page first loads, if so trigger pop-up then change state value to false, but the boolean state value is persisted and cannot seem to be changed so each time you refresh the page, the value changes back to true so the pop-up fires.

If anybody can advise or perhaps knows of a better way to handle this type of pop-up between routes in React I would appreciate it?

Here's my code:

Form component onSubmit function:

    const navigate = useNavigate();

    const onSubmit = async (values: ClientFormValues): Promise<ApiError | undefined> => {
        const createClientResponse = await createClient(values);
        console.log("client response on submit = ", createClientResponse);
        if (!createClientResponse.success) return createClientResponse.error;

        navigate(appPaths.clients.index, {state: {formSubmitted: null}});
    };

Redirected page:

    const [open, setOpen] = useState(false);
    const location = useLocation();
    const state = location.state as { formSubmitted?: boolean };

    const handleOpenAlert = () => {
        setOpen(true);
    };
    const handleCloseAlert = () => {
        setOpen(false);
    };

    useEffect(() => {
        if (state && state.formSubmitted) {
            handleOpenAlert();
            state.formSubmitted = false;
        }
    }, []);

In the receiving component you should clear the state via a new navigation action instead of trying to mutate it.

Use a redirect to the current path, without state, to REPLACE the current entry in the history stack.

Example:

const location = useLocation();
const navigate = useNavigate();

const [open, setOpen] = useState(false);

const state = location.state as { formSubmitted?: boolean };

const handleOpenAlert = () => {
  setOpen(true);
};
const handleCloseAlert = () => {
  setOpen(false);
};

useEffect(() => {
  if (state && state.formSubmitted) {
    handleOpenAlert();
    navigate(".", { replace: true }); // redirect to current path sans state
  }
}, [navigate, state]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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