5

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){}
  });
}
4

1 回答 1

3

如果您使用的是 redux-saga(这很棒),您可以使用调用效果将 cognitoUser.authenticateUser 之类的 asyc 回调转换为一组要由中间位置执行的指令。

当中间件解析调用时,它将通过生成器单步执行下一个 yield 语句,您可以将返回结果分配给一个变量,然后您可以使用 put 效果将其置于您的状态中。

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);

  // Note: since you're invoking an object method
  // you'll want to pass the object's context (this) with the call via an array

  const token = yield apply(cognitoUser, cognitoUser.authenticateUser, [authenticationDetails, { onSuccess(response){return response}, onFailure(){} }]);

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

我强烈推荐这个令人难以置信的教程。

编辑:为简洁起见,您遗漏了一些代码,但我强烈建议您将代码包装在尝试捕获中的生成器中,因为您依赖于 API 的外部 IO。

于 2016-08-02T01:40:45.297 回答