0

I want to save the token in the cookie and run the navigation ("/"). In "/", it is implemented so that the token value is implemented. Therefore, I want to use setCookie to run navigate after the token value comes in. I think we should use async await, so we tried a lot, but we failed.(I'm using the react-cookie library.)

  const [cookies, setCookie, removeCookie] = useCookies("token");
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);
          // navigate("/");
        }
      })
      .catch((err) => {
        console.log("==>", err);
 
      });
Error: Request failed with status code 401
    at createError (createError.js:16:1)
    at settle (settle.js:17:1)
    at XMLHttpRequest.onloadend (xhr.js:66:1)

김유경
  • 59
  • 1
  • 5
  • You could do with `async`/`await`, sure, but right now as it stands, `setCookie` is only ever called after the request finishes and the condition is meet. The code, in that way, looks correct to me. – Alejandro Feb 02 '22 at 14:54
  • An error occurs in the code above. I think it's because we went over to navigate ("/") before "token" was created with setCookie. – 김유경 Feb 02 '22 at 14:59
  • 1
    You have an unhandled error. You should add a `.catch` after the `.then` It seems there is an issue with your api call since it returns [401 Unauthorized](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401) – SamiElk Feb 02 '22 at 15:07
  • The error message is an error message received from .catch. When I took the console.log() `setCookie("token", response.data.account_token, { path: "/", }); navigate("/");` When annotated, the response.data value could be returned from .then normally. – 김유경 Feb 02 '22 at 15:14

2 Answers2

0
async method(){
   const [cookies, setCookie, removeCookie] = useCookies("token");
 try{
    var response= await axios.post(`${process.env.REACT_APP_API}/normal_login/`, formData);
    if (response.data) {
       console.log(response.data.account_token);
       setCookie("token", response.data.account_token, {
       path: "/",
       });
       console.log("cookies", cookies);
          // navigate("/");
       }
  }
 catch(e){
   console.log(e);
 }
}
sai kiran
  • 389
  • 2
  • 10
0

You could use a useEffect with cookie as a dependencie to trigger something after the cookie changes. Something like:

useEffect(() => navigate('/'), [cookies]);

Adding the dependencie to the useEffect make it act only when the variable (here cookie) in the dependencie is modified.

Quentin Grisel
  • 4,794
  • 1
  • 10
  • 15