如何在 React 的不同文件中从 API 调用中获取数据

How do I get the data from an API call, in a different file, in React

考虑到新的 SDK 版本,我正在尝试更新一些代码。我在一个文件中有新的 api 调用:

import { CognitoIdentityProviderClient, ListUsersCommand } from "@aws-sdk/client-cognito-identity-provider";
import awsmobile from "../../aws-exports";
import { Auth } from "aws-amplify";

export default async function ListUsers() {
      await Auth.currentCredentials().then((data) => {
        const client = new CognitoIdentityProviderClient({
          region: awsmobile.aws_project_region,
          credentials: data
        });
        const params = {
          UserPoolId: awsmobile.aws_user_pools_id
        };
        const command = new ListUsersCommand(params);
        client.send(command).then(
          (data) => {
            return data
          },
          (error) => {
            console.log(error)
          }
        );
      });
}

我正在尝试检索另一个文件中的数据:

import ListUsers from "../../../API/cognito/ListUsers";
import ListUsersInGroup from "../../../API/cognito/ListUsersInGroup";
import { useState, useEffect, useRef } from "react";
import PortalUsersTable from "../../../components/tables/PortalUsersTable";

export default function ManageUsers() {
  const [userDetails, setUserDetails] = useState("");
  const refUsers = useRef();
  const refUsersExec = useRef();
  const refUsersAdmin = useRef();
  const refUsersGroups = useRef();

  useEffect(() => {
    function getUsers() {
      refUsers.current = ListUsers();

      refUsersExec.current = ListUsersInGroup("usersAdmin");

      refUsersAdmin.current = ListUsersInGroup("usersExec");
      //setUsersTloOfficers(apiTloOfficers);

      refUsersGroups.current = ListUsersInGroup("usersGroups");
    
      let userData = [];

      let arrUsersExec = [];
      for (let a in refUsersExec.current.Users) {
        arrUsersExec.push(refUsersExec.current.Users[a].Username);
      }

      let arrUsersAdmin = [];
      for (let b in refUsersAdmin.current.Users) {
        arrUsersAdmin.push(refUsersAdmin.current.Users[b].Username);
      }

      let arrUsersGroups = [];
      for (let b in refUsersNtigGroups.current.Users) {
        arrUsersGroups.push(refUsersGroups.current.Users[b].Username);
      }

      for (let i in refUsers.current.Users) {
        let email = null;
        for (let x in refUsers.current.Users[i].Attributes) {
          if (refUsers.current.Users[i].Attributes[x].Name === "email") {
            email = refUsers.current.Users[i].Attributes[x].Value;
            break;
          }
        }
        let memberExec = arrUsersExec.includes(refUsers.current.Users[i].Username);
        let memberAdmin = arrUsersAdmin.includes(refUsers.current.Users[i].Username);
        let memberGroups = arrUsersGroups.includes(refUsers.current.Users[i].Username);

        userData.push({
          id: i,
          Username: refUsers.current.Users[i].Username,
          AccountStatus: refUsers.current.Users[i].UserStatus,
          Email: email,
          Users: memberGroups,
          Exec: memberExec,
          Admin: memberAdmin,
          
        });
      }
      setUserDetails(userData);
    }
    getUsers();
  }, []);

  return (
    <>
      <h2>Manage Portal Users</h2>
      <PortalUsersTable userDetails={userDetails} />
   
    </>
  );
}

处理 API 数据的逻辑是合理的。

这是旧的 API 调用:

import AWS from "aws-sdk";
import awsmobile from "../../aws-exports";
import { Auth } from "aws-amplify";

export default async function ListUsers() {
  let idToken = "";
  await Auth.currentAuthenticatedUser().then((user) => {
    idToken = user.signInUserSession.idToken.getJwtToken();
  });

  AWS.config.region = awsmobile.aws_cognito_region;
  AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: awsmobile.aws_cognito_identity_pool_id,
    RoleArn: "arn:aws:iam::xxxxxxxxx:role/xxxxxxxxxxxxx",
    Logins: { "xxxxxxxxxxxxxxxxxxxx": idToken }
  });

  let cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
  let params = {
    UserPoolId: awsmobile.aws_user_pools_id,
    AttributesToGet: ["email"]
  };
  return new Promise((resolve, reject) => {
    cognitoidentityserviceprovider.listUsers(params, function (err, result) {
      if (err) {
        console.log(err);
        //onError(err);
        reject(err);
        return;
      }
      if (result) {
        resolve(result);
      }
    });
  });
}

我可以看到新的 API 调用在控制台中返回了正确的数据。我想我没有正确地在文件之间传递数据。

我已经尝试了多种更改 API 调用函数的方法,阅读了 cognito sdk 描述,但不正确的不是 API 调用。

如何在单独的文件中使用 API 通话数据?

即使您的 API 调用正确,看起来您也没有从函数 ListUsers 返回任何内容。您将 async/await 模式与 then 混合在一起。我假设您在 return data 之前添加了 console.log。使用 async/await 重构您的函数将如下所示:

export default async function ListUsers() {
  try {
    const data = await Auth.currentCredentials();
    const client = new CognitoIdentityProviderClient({
      region: awsmobile.aws_project_region,
      credentials: data,
    });
    const params = {
      UserPoolId: awsmobile.aws_user_pools_id,
    };
    const command = new ListUsersCommand(params);
    const commandData = await client.send(command);
    return commandData;
  } catch (error) {
    console.log(error);
  }
}