-1

How do I return data with promise? my below code works fine but when I switch this to promise, it does not return any data.

export function userSignupRequest(username, password) {

  return (dispatch) => {
    if (username === 'hello@world.com' && password === 'admin') {
       console.log('Sign up success')
       dispatch(setLoginSuccess(true));
       return userAccountDataFromSever
     } else {
       console.log('Sing up failed')
       return new Error('Will be an error message from server')
     }    
  }
}

I get either userAccountDataFromSever or new Error('Will be an error message from server') from above code by console.log(userSignupRequest(email, password)) However, when I switched this to below, it returned undefined.

export function userSignupRequest(username, password) {

  return (dispatch) => {
    Auth.signUp({
        username,
        password
    })
    .then(data => {
      console.log(data)
      dispatch(setLoginSuccess(true));
      return data;
    })
    .catch(err => {
      console.log(err)
      return new Error(err.message)
    });

  }
}

How do I make this work?

Skate to Eat
  • 2,554
  • 5
  • 21
  • 53

1 Answers1

2

Since userSignupRequest will do asynchronous operations, it becomes an asynchronous function.

The current way to 'return' values in async function is returning a promise and then using the .then().catch() syntax.

Example of your function returning a promise:

export function userSignupRequest(username, password) {
  return (dispatch) => {
    return new Promise((resolve, reject) => {
      Auth.signUp({
          username,
          password
      })
      .then(data => {
        console.log(data)
        dispatch(setLoginSuccess(true));
        return resolve(data);
      })
      .catch(err => {
        console.log(err)
        return reject(err);
      });
    });
  }
}

Example of use:

userSignupRequest('admin', 'admin')(dispatch)
  .then(user => console.log(`User ${user} signed up!`)
  .catch(err => console.error(err);
Gregoire Lodi
  • 557
  • 2
  • 10