margherita pizza
margherita pizza

Reputation: 7145

Handle promises inside redux actions with thunk

I have a fake login function like this

const login = (email, password) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (email === "[email protected]" && password === "demo1234") {
        resolve(200);
      } else {
        reject(401);
      }
    }, 1000);
  });
};

This is my authAction.js file

export const login = (email,password) => async(dispatch) => {
  try {
    await fakeLogin(email,password)
    dispatch({
      type:LOGIN,
      payload:{}
    })
    
  } catch (error) {
    console.log(error)
  }
}

In my LoginPage.js react component I call the action like this

 const submit = ({ email, password }) => {
    props.login(email, password).then((e) => console.log("then",e)).catch(err=>console.log("ca"));
  };

If I pass the wrong credentials it logs the error code 401 inside the action. But in the LoginPage component, it always comes to the then block and prints undefined.

Even if I pass the right credentials it comes to then block and prints 'undefined'

But If I modify the action to return 200 or the error

export const login = (email,password) => async(dispatch) => {
  try {
    await fakeLogin(email,password)
     dispatch({
      type:LOGIN,
      payload:{}
    })
    return 200
    
  } catch (error) {
    return error;
  }
}

Now it prints the error code in "then" block of the LoginPage component.

Simply I want to inform the LoginPage component of what happened to the request. So what I am doing right now is okay or is there any other performance optimal way to do this?

Any help Thanks in advance!

Upvotes: 0

Views: 63

Answers (1)

Viet
Viet

Reputation: 12777

You forgot return value in then and throw error in catch

export const login = (email,password) => async(dispatch) => {
  try {
    const res = await fakeLogin(email,password)
    dispatch({
      type:LOGIN,
      payload:{}
    })
    return res
    
  } catch (error) {
    console.log(error)
    throw error
  }
}

Upvotes: 1

Related Questions