How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me.

I am feeling quite lost on how to properly integrate the information retrieved from the API into my component. My previous solution attempt is currently commented out.

I am aware that there are likely several flaws in my code, so any guidance on debugging or enhancing the React functionality would be greatly 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 className="role"><span>{role}</span></small>
            </div>
        </div>
    )
}

export default agentCard;

Answer №1

Here are a few more things that need attention:

  1. Make sure to set the API response to a component state using the useState hook.

  2. Remember, React component names should always start with a capital letter as per convention. You can adjust this at the import time too.

import AgentCard from "./agentCard";

Consider making the following changes:

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

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

  // Rest of the code for fetching and rendering agent details

View Code Sandbox example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue with React router that reads: "TypeError: type.toUpperCase is not a function."

I'm currently working on building an isomorphic app that utilizes react and express.js. For client-side routing, I am using React Router. However, during the app's runtime, I encountered several errors and warnings in the console: Warning: Faile ...

Troubleshooting jQuery's issue with dynamically adding input fields

I came across a tutorial (which I tweaked slightly) on this website: code In JSFiddle, everything works perfectly fine with the code. However, when I implemented it on my actual page, it's not functioning as expected. I've been trying to trouble ...

Working with HTML5 Canvas to Clip Images

Is there a way to implement a tileset image in canvas like this one? I am trying to figure out how to make it so that clicking on the first tile returns 0, clicking on the tenth tile returns 9, and so on... Any suggestions on how to clip a tileset on an ...

Dragging the world map in D3 causes it to appear jumpy and erratic

I'm currently working on a Vue project to create an interactive world map that allows users to drag and zoom. I've attempted to integrate D3 for this purpose, but encountered an issue where the map jumps to the bottom right of the page whenever I ...

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

The Protected Routes in React Router Dom persistently redirecting

I am currently implementing protected routes in my Redux and Pure React app using React Router Dom. The issue I am facing is that when I navigate to /profile/edit and then refresh the page, it automatically redirects me to /login and then to /profile. I ha ...

Why am I encountering a 400 error with my mutation in Apollo Client, when I have no issues running it in Playground?

After successfully testing a mutation in the playground, I attempted to implement it in my Apollo client on React. However, I encountered an error message stating: Unhandled Rejection (Error): Network error: Response not successful: Received status code 40 ...

Dynamic text displayed on an image with hover effect using JavaScript

Currently, I am in the process of developing a website for a coding course that is part of my university curriculum. The project specifications require the use of JavaScript, so I have incorporated it to display text over images when they are hovered over ...

Tips for creating animations with JavaScript on a webpage

I created a navigation bar for practice and attempted to show or hide its content only when its title is clicked. I successfully toggled a hidden class on and off, but I also wanted it to transition and slide down instead of just appearing suddenly. Unfort ...

React-Native Error: Invalid element type detected

While attempting to run my React Native app on my iPhone using Expo, I encountered an error displayed in a red background area. Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

How can we optimize axios requests with lodash debounce?

Utilizing a state prop named network busy status to control elements in the UI. Due to the rapid changes in status, my spinner appears overly active. Is there a simple method, utilizing lodash _.debounce, to throttle this section of code? const instance ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...

Develop a custom npm package with dependencies stored locally and add it to a different package during installation

I have developed three unique custom modules. getcorrespondence-1.0.0.tgz getrediscache-1.0.0.tgz setrediscache-1.0.0.tgz These custom node modules were created using the command npm pack. The module getcorrespondence-1.0.0.tgz has dependencies on two o ...

Revise for embedded frame contents

Is it possible to modify the HTML content of an iframe within a webpage? I currently have this code snippet: <iframe src="sample.html"></iframe> I am looking for a way to edit the contents of sample.html without directly altering the HTML co ...

"Exploring the possibilities of Ajax in conjunction with Sol

I recently completed a tutorial on Ajax Solr and followed the instructions in step one. Below is the code I wrote: header.php: <script type="text/javascript" src="static/js/ajax-solr/core/Core.js"></script> <script type="text/javascript" s ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

How to efficiently send multiple objects in response to a single GET request with Express and Node.js

The code snippet I am working with looks like this - sendServer.get('/download',function(request,response){ var status="SELECT * from poetserver.download where status='0'"; console.log(status) connection.query(status,function(error,ro ...

ES5 enables the extension of classes in React

This ES6 syntax works fine for me: import {Component} from 'react'; class A extends Component {} class B extends A { // I can redeclare some methods here } But how would one implement this using ES5? Like so: var React = require('reac ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...

Next.js and Material UI - issues with dynamic styles not functioning

I recently started using Next JS in combination with Material UI, following the example project setup provided in the documentation on Github: https://github.com/mui-org/material-ui/tree/master/examples/nextjs My main objective is to utilize Material UI&a ...