'How to use async-await in onsubmithandler

I put the login authentication function and navigation function in the onsubmitandler. "/" requires a token value in the cookie so that it can go to the router. But if you look at my code, it goes to "/" before the setCookie is executed and an error occurs. I want to make sure that 'navigate ("/");' is executed after the setCookie is executed.


  const [cookies, setCookie, removeCookie] = useCookies("token");

 const onSubmitHandler = (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append("nickname", Nickname);
    formData.append("password", Password);
    axios
      .post(`${process.env.REACT_APP_API}/normal_login/`, formData)
      .then((response) => {
        if (response.data) {
          console.log(response.data.account_token);
          setCookie("token", response.data.account_token, {
            path: "/",
          });
          console.log("cookies", cookies); // null
        }
        navigate("/");
      })
      .catch((err) => {
        console.log("==>", err);
      });
  };


Solution 1:[1]

useCookies does not have any promise functions, however you can use a addChangeListener, and navigate when the cookie is changed. Though I suspect the real problem lies in your deconstructor.

Currently you are trying to deconstruct an array, but useCookies returns an object, so replace your [] with {}. If done correctly your deconstructor should look like the following.

const {cookies, setCookie, removeCookie} = useCookies("token");

If changing your deconstructor didn't work you could use the following example to solve your problem.

const {cookies, setCookie, removeCookie, addChangeListener} = useCookies("token");

addChangeListener( () => {
    navigate("/");
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1