Home > front end >  react inside loop with two different API request
react inside loop with two different API request

Time:10-29

https://i.stack.imgur.com/RaoRC.jpg https://i.stack.imgur.com/fPge5.jpg

i have this to fetch two different API's.

API #1 Fetches the Name not organized by ranking API #2 Fetches the ID of the name Organized by ranking, so i need to do a inside loop if the ID and Name Matches to get the Name of the player.

Something like this i did on Async fuction

    <script>
        getData();


        async function getData() {
            const response = await fetch('http://localhost:3008/api/highscore/players')
            console.log(response);
            const data = await response.json();
            const req = await fetch('http://localhost:3008/api/players')
            console.log(req);
            const info = await req.json();
            length = data.players.length;
            console.log(data);
            var temp = "";
            for (i = 0; i < length; i  )
                for (j = 0; j < length; j  )  {
                    {


                        if (info.players[i].id == data.players[j].id) {

                            temp  = "<tr>";
                            temp  = "<td>"   data.players[j].position   "</td>";
                            temp  = "<td>"   info.players[i].name   "</td>";
                            temp  = "<td>"   data.players[j].score   "</td>";
                            temp  = "</tr>";
                        }

                    }
                }
            document.getElementById("data").innerHTML = temp;
        }

This is my React APP Code where i need it done : How can i go about it? any idea? any help will be deeply appreciate it!

import axios from "axios";
import React, { useState, useEffect } from "react";

const Ranking = () => {
  const [playerName, setPlayerName] = useState([]);
  const [playerRank, setPlayerRank] = useState([]);

  const fetchData = () => {
    const playerAPI = 'http://localhost:3008/api/players';
    const playerRank = 'http://localhost:3008/api/highscore/players';

    const getINFOPlayer = axios.get(playerAPI)
    const getPlayerRank = axios.get(playerRank)
    axios.all([getINFOPlayer, getPlayerRank]).then(
      axios.spread((...allData) => {
        const allDataPlayer = allData[0].data.players
        const getINFOPlayerRank = allData[1].data.players

        setPlayerName(allDataPlayer)
        setPlayerRank(getINFOPlayerRank)
      })
    )
  }
  
  useEffect(() => {
    fetchData()
  }, [])

  return (
    <table >
      <tr>
        <th>Rank</th>
        <th>Name</th>
        <th>Points</th>
      </tr>
        <tbody>
          {playerName?.map((name) => {
            return (
              <tr key={name.name}>
                <td>{name.name}</td>
              </tr>
            )
          })}
        </tbody>


    </table>
  )
}

export default Ranking

CodePudding user response:

this is the rendered content output

What type of backend language you use? or you are using remote server? this can be done on the backend, but only if you have access to it. Spring boot is amazing at this, with ORM you can Easly map tables using @ManyToOne or @OneToMany relation. I can do this for you if you want, please contact me.

if you just want to go with your code, or you are getting the response from a remote server, then fetch the responses, put the data in playerInf and rankInfo states, respectively. after use this code directly in return method:

// in your app add the following functions, replace the url and call them in useEffect hook or in the function of your choice.

import React, {useState, useEffect} from 'react';
function App(props) {
    useEffect(()=> {
       // get the data from the website every 24 hours
       const intervalId = setInterval(() => {
          playerInfoData();
          playerRankData();
       }, 86400000);
       return ()=> {
            clearInterval(intervalId);
        };
    },[]);

    const playerInfoData = () => {
            fetch(`resources/jsons/player.json`,//replace your url here
                {   
                headers : { 
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
                
            }).then(res => res.json()).then(
                data => {
                    setPlayerInfo(data);
                    setReady(true);
                    
            }).catch(error => {
                console.log(error);
            });
            
        }
        const playerRankData = () => {
            fetch(`resources/jsons/rank.json`,
                {   
                headers : { 
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
                
            }).then(res => res.json()).then(
                data => {
                    setRankInfo(data);
                    setReady(true);
                    
            }).catch(error => {
                console.log(error);
            });
        }
    // ready is used to tell react to not render unless data is ready
    return (
    {ready && playerInfo.map(player => {
                
                    return (
                          <tr key={player.name}>
                            <td>{ready && rankInfo.map(rank => {
                                if(player.id === rank.id){
                                    return rank.value;
                                }
                            })
                            }</td>
                            <td>{player.name}</td>
                            <td>{player.points}</td>
                          </tr>
                        )
                      })
                  }
            )

}

again, this is not good practice, always do your logic in backend and customize the response. I can help you with that, contact me if you want to know more.

  • Related