Home > Software design >  how to call function after async task react
how to call function after async task react

Time:03-11

i want to navigate to dashboard after login and dashboard is protected route

const handleLogin = (e) => {
    e.preventDefault();
    if (email || password) {
      dispatch(loginUser({ email, password }));
      navigate("/dashboard");
    } else {
      toast.error("Please Enter Email and Password");
    }
  };
i am using redux toolkit createAsyncThunk for api request

export const loginUser = createAsyncThunk("auth/login", async (userDetails) => {
  try {
    const { email, password } = userDetails;
    const res = await fetch("http://localhost:5000/api/users/login", {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email,
        password,
      }),
    });
    const result = await res.json();
    if (result.error) {
      toast.error(result.error);
    } else {
      toast.success("Login successfull");
      localStorage.setItem("user", JSON.stringify(result));
      return result;
    }
  } catch (error) {
    console.log(error);
  }
});
when i click on login it try to navigate the page before the state update what i want the navigate function wait untill the api respone recieve then navigate to dashboard

CodePudding user response:

dispatch(loginUser({ email, password })); returns a promise, you can wait for the promise to resolve before doing additional work:

const handleLogin = () => {
  dispatch(loginUser({ email, password })).then(() => {
    navigate("/dashboard");
  })
}

see Unwrapping Result Actions

  • Related