React JSX Question

Call yield put() inside a success callback

I am brand new to React and Redux.

I am using react-redux to call the AWS Cognito service which takes an object containing a success and failure callback. I get my JWT back from AWS Cognito when I console.log inside my success callback; however, how can I

yield put()
inside this callback since it's not a generator function (
function*
).

Here's some code:



export function* getAWSToken(){
// username, password and userPool come from react state
// not showing code for brevity.

const userData = {
Username: username,
Pool: userPool,
};
const authenticationData = {
Username : username,
Password : password,
};

const cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
const authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);

// This here is the callback
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess(result){
yield put(cognitoTokenObtained(result.getIdToken().getJwtToken())
},
onFailure(err){}
});
}

Answer

If you're using redux-saga (which is awesome), you can use the call effect to transform an asyc callback like cognitoUser.authenticateUser into a set of instructions to be executed by the middlewhere.

When the middleware resolves the call it will step through the generator to the next yield statement, you can assign the return result to a variable that you can then place in your state using a put effect.

export function* getAWSToken(){
  // username, password and userPool come from react state
  // not showing code for brevity.

  const userData = {
      Username: username,
      Pool: userPool,
    };
  const authenticationData = {
    Username : username,
    Password : password,
  };

  const cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
  const authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);

  const token = yield call(cognitoUser.authenticateUser, authenticationDetails);

  yield put(cognitoTokenObtained(token.getIdToken().getJwtToken());
}

There's also this incredible tutorial I'd highly recommend.

Edit: You left out some code for brevity, but I'd highly recommend wrapping the code inside the generator in try catches since you're depending on external IO from an API.