Bisma
Bisma

Reputation: 361

dispatching two actions one after the other in react asyncronously

Im dispatching two actions one after the other, where the second dispatch makes use of the reducer of first dispatch, but im getting undefined as the second action gets dispatched before the first action is dispatched.

Here is my code:

const auth = useSelector((state) => state.auth);
const student = useSelector((state) => state.student);

useEffect(() => {
    const id = auth.user.user;
    dispatch(getStudent(id));
  }, [auth.authenticate]);

if (auth.authenticate) {
    if (auth.user.user_type.is_student == true) {
      if (student.detail && student.detail.length > 0) {
        return <Redirect to={"/student/classes"}></Redirect>;
      } else {
        return <Redirect to={"/student/profile"}></Redirect>;
      }
    } else {
      return <Redirect to={"/faculty/classes"}></Redirect>;
    }
  }
const userLogin = (e) => {
    e.preventDefault();
    const user = {
      username,
      password,
    };
    dispatch(login(user));
    
    
  };

im trying to redirect it to the pages depending on whether student.detail is populated or not, but it redirects first and executed useEffect function later.

Upvotes: 1

Views: 503

Answers (1)

Janmey Solanki
Janmey Solanki

Reputation: 11

useEffect(() => {
if(auth && auth.user && student.detail.length == 0) {
  const id= auth.user.user
  console.log(id)
  dispatch(getStudent(id));
}, [auth]);

Dispatch the second action once the auth state in store is updated so that you will git the desired user id.

Or

Use async/await.

Upvotes: 1

Related Questions