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

Time:02-03

I'm trying to update some code, taking into account new sdk versions. I have the new api call in one file:

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

I'm trying to retrive the data in another file:

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

The logic to handle the API data is sound.

This is the old API call:

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

I can see the new API call is returning the correct data in the console. I think I'm not passing the data between files correctly.

I've tried various ways of changing the API call function, reading the cognito sdk description but it's not the API call that is incorrect.

How can I use the API call data in the separate file?

CodePudding user response:

Even if your API call if correct, it looks like you are not returning anything from your function ListUsers. You are mixing async/await pattern with the then. I assume you have added a console.log right before the return data. Refactoring your function using async/await would look like this :

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);
  }
}
  •  Tags:  
  • Related