React: How should I populate the HTML?

I’ve been just following a mix of tutorials on React. I used an API to get my data. I don’t think the way I did is efficient but the code I looked at didn’t work.

I’m completely lost as to how I should approach getting the info I got from the API into the component. My last attempt at a solution is commented out.

I’m sure there’s probably a few things fundamentally wrong with my code, so anything that would help fix my code or incorporate more aspects of React would be much appreciated.

App.js

import { useEffect } from "react";

function App() {
  const getAllAgents = async () => {
    const res = await fetch('https://valorant-api.com/v1/agents/')
    const results = await res.json()

    const agentNames = [], agentImages = [], agentRoles = []
    const agentDetails = []

    for (let i = 0; i < Object.keys(results["data"]).length; i++) {
      if (results["data"][i]["developerName"] == 'Hunter_NPE') {
        continue
      }
      else {
        agentNames.push(results["data"][i]["displayName"])
        agentImages.push(results["data"][i]["displayIcon"])
        agentRoles.push(results["data"][i]["role"]["displayName"])
      }
    }

    for (let i = 0; i < agentNames.length; i++) {
      agentDetails[i] = [agentNames[i], [agentImages[i], agentRoles[i]]]
    }
    agentDetails.sort();
    //console.log(agentDetails)
  }

  useEffect(() => {
    getAllAgents()
  }, [])

  return (
    <div className="app-container">
      <h3>Valorant</h3>
      <div id="agent_container" className="agent-container">
      {/*getAllAgents.map((agentDetails) =>
        <agentCard 
          img={agentDetails[1][0]}
          name={agentDetails[0]}
          role={agentDetails[1][1]}
      />)*/}
      </div>
    </div>
  );
}

export default App;

agentCard.js

import React from 'react'

const agentCard = ({role, name, img}) => {
    return (
        <div card-container>
            <div className="img-container">
                <img src={img} alt={name} />
            </div>
            <div className="info">
                <h3 className="name">{name}</h3>
                <small class="role"><span>{role}</span></small>
            </div>
        </div>
    )
}

export default agentCard

Answer

Few more things to do / correct,

  1. You need to set the API response to a component state. You should use the useState hook for that.

  2. React component names should start with a capital first letter. You can either correct it at the import time as well. Better to follow some convention.

import AgentCard from "./agentCard";

Try like below.

import { useEffect, useState } from "react";
import AgentCard from "./agentCard";

function App() {
  const [agentDetails, setAgentDetails] = useState([]);

  const getAllAgents = async () => {
    const res = await fetch("https://valorant-api.com/v1/agents/");
    const results = await res.json();

    const agentNames = [],
      agentImages = [],
      agentRoles = [];
    const agentDetails = [];

    for (let i = 0; i < Object.keys(results["data"]).length; i++) {
      if (results["data"][i]["developerName"] == "Hunter_NPE") {
        continue;
      } else {
        agentNames.push(results["data"][i]["displayName"]);
        agentImages.push(results["data"][i]["displayIcon"]);
        agentRoles.push(results["data"][i]["role"]["displayName"]);
      }
    }

    for (let i = 0; i < agentNames.length; i++) {
      agentDetails[i] = [agentNames[i], [agentImages[i], agentRoles[i]]];
    }
    agentDetails.sort();
    setAgentDetails(agentDetails);
  };

  useEffect(() => {
    getAllAgents();
  }, []);

  return (
    <div className="app-container">
      <h3>Valorant</h3>
      <div id="agent_container" className="agent-container">
        {agentDetails.map((agentDetails) => (
          <AgentCard
            img={agentDetails[1][0]}
            name={agentDetails[0]}
            role={agentDetails[1][1]}
          />
        ))}
      </div>
    </div>
  );
}

export default App;

Code Sandbox

Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .