Itterate over an array in reactjs Using a json fetch from an Api?

Hello!
I’m new to react, I’m using the Riot game API to fetch some data.
Here I fetch the last match history and get everything I need, Names of the player… stats ect, this json is simple I understand it.

Now, Here comes the problem, In the api I get a championId (The character that you play in), but not the name of the champion, in order to get the name riot give us a json file (http://ddragon.leagueoflegends.com/cdn/10.9.1/data/en_US/champion.json).
It looks like this :

So I have the key, for example 106, But I dont know how to associate it with the json (Which I fetch) and get the name of the character.

I tried a lot of things like map, but always send me the same error " Cannot read property ‘map’ of undefined " Because the json file is like
{“Aatrox”:{“version”:“10.9.1”,“id”:“Aatrox”,“key”:“266”,“name”:“Aatrox”}…
So it’s really confusing I really dont know how to write it.

So yeah, I really dont know if you guys can help me/ give me some advice

Thanks a lot

Ps : Here’s my actual code :

import React, {Component} from 'react';
import axios from 'axios';

class App extends Component {


    constructor(props) {
        super(props);
        this.state = {
            items: [],
            summonername: '',
            token: "SecretTokenHere",
            id: '',
            champions: {},
        };
        this.updateInput = this.updateInput.bind(this);
        this.apiSummoner = this.apiSummoner.bind(this);
        this.apiAccount = this.apiAccount.bind(this);
        this.onClick = this.onClick.bind(this);
    }

    updateInput(event) {
        this.setState({summonername: event.target.value})
    }


    async apiSummoner() {   // Get summonner information
        let summonername = this.state.summonername;
        const summonerurl = `/summoner/v4/summoners/by-name/${summonername}`;

        await axios.get(summonerurl, { //Attendre le résultat de la promesse d'axios
            params: {}, headers: {
                'X-Riot-Token': this.state.token
            },
        })
            .then(res => {
                console.log(res);
                this.setState({summonersname: res.data.name});
                this.setState({summonerslevel: res.data.summonerLevel});
                this.setState({summonersid: res.data.accountId});
            })
            .catch(error => {
                console.log("An error occured on  apiSummoner D: ", error);
            });

    };


    async apiAccount() { // get Last matchId of the summoner
        let summonerId = this.state.summonersid;
        const matchurl = `/match/v4/matchlists/by-account/${summonerId}`;
        await axios.get(matchurl, {
            params: {},
            headers: {'X-Riot-Token': this.state.token}
        })
            .then(res => {
                console.log(res);
                this.setState({matchId: res.data.matches[0].gameId});
                this.setState({matchchampion: res.data.matches[0].champion});
                this.setState({matchlane: res.data.matches[0].lane})
            })
            .catch(error => {
                console.log("An error occured on apiAccount D: ", error)
            })
    }

    async apiGame() {
        let matchID = this.state.matchId;
        const gameurl = `/match/v4/matches/${matchID}`;
        await axios.get(gameurl, {
            params: {},
            headers: {'X-Riot-Token': this.state.token}
        })
            .then(res => {
                console.log(res);
                this.setState({participant1: res.data.participantIdentities[0].player.summonerName});
                this.setState({participant2: res.data.participantIdentities[1].player.summonerName});
                this.setState({participant3: res.data.participantIdentities[2].player.summonerName});
                this.setState({participant4: res.data.participantIdentities[3].player.summonerName});
                this.setState({participant5: res.data.participantIdentities[4].player.summonerName});
                this.setState({participant6: res.data.participantIdentities[5].player.summonerName});
                this.setState({participant7: res.data.participantIdentities[6].player.summonerName});
                this.setState({participant8: res.data.participantIdentities[7].player.summonerName});
                this.setState({participant9: res.data.participantIdentities[8].player.summonerName});
                this.setState({participant10: res.data.participantIdentities[9].player.summonerName});
                this.setState({participantchamp1: res.data.participants[0].championId});
                this.setState({participantchamp2: res.data.participants[1].championId});
                this.setState({participantchamp3: res.data.participants[2].championId});
                this.setState({participantchamp4: res.data.participants[3].championId});
                this.setState({participantchamp5: res.data.participants[4].championId});
                this.setState({participantchamp6: res.data.participants[5].championId});
                this.setState({participantchamp7: res.data.participants[6].championId});
                this.setState({participantchamp8: res.data.participants[7].championId});
                this.setState({participantchamp9: res.data.participants[8].championId});
                this.setState({participantchamp10: res.data.participants[9].championId});

                console.log(this.state.participantchamp1)
            })
            .catch(error => {
                console.log("An error occured on apiGame D: ", error)
            })

    }


    componentDidMount() {
        fetch('http://ddragon.leagueoflegends.com/cdn/10.9.1/data/en_US/champion.json')
            .then(response => response.json())
            .then(res => {
                const champions = res;
                console.log(champions);
                this.setState({champions: res.data});
                console.log(this.state)
                    .catch(error => console.log(error))


            })
    }
    
    

    async onClick() {
        try {
            await this.apiSummoner();
        } catch (e) {
            console.log("error : ", e)
        }
        console.log("It must wait");
        try {
            await this.apiAccount()
        } catch (e) {
            console.log("error", e)
        }
        try {
            await this.apiGame()
        } catch (e) {
            console.log("error", e)
        }
    }

    render() {
       let  {test} = this.state;
        return (

            <div>
                <label className={"label"}>
                    <input type="text" onChange={this.updateInput}/>
                    <input type="submit" onClick={this.onClick} value="Search"/>
                </label>
                <div> Name : {this.state.summonersname}  </div>
                <br/>
                <div> Level : {this.state.summonerslevel} </div>
                <br/>
                <h1> Last Match : </h1>

                <br/>
                <h4> Blue Side </h4>
                <div> : {this.state.participant1} -></div>
                <div> : {this.state.participant2} </div>
                <div> : {this.state.participant3} </div>
                <div> : {this.state.participant4} </div>
                <div> : {this.state.participant5} </div>
                <br/>
                <h4> Red Side </h4>
                <div> : {this.state.participant6} </div>
                <div> : {this.state.participant7} </div>
                <div> : {this.state.participant8} </div>
                <div> : {this.state.participant9} </div>
                <div> : {this.state.participant10} </div>
                <br/>

                {console.log(this.state.champions)}

            </div>
        );

    }


}
export default App;


I’m not quite sure if this will answer your question, but to convert the championId that you’re getting from the API into a full champion object that you can get the champion’s information from, this is what I would do:
Make a function, and pass the json file’s data into it, along with the champion’s id.
Let’s say you save the json data as a variable, champions.

function getChampionById (data, id) {
  // This gets you a list of all the keys in champions.data
  let dataKeys = Object.keys(data);
  // Iterate through them, and pull out the one that matches the championId that you want
  for (let key of dataKeys) {
    if (data[key].key == id) {
      return data[key];
    }
  }
  // Return something if that number doesn't exist.
  return {error: "Champion not found"}
}

let championInfo = getChampionById(champions.data, "106");

Edited: Passed dumb parameters at first, fixed now.

Hi Luos !

Thanks for your fast answer, it’s really appreciated !

I understand what you are doing, it’s a big help for me, thanks.

Here what i’m trying to do is for example

I’ll get the 10 participant of the game when I fetch the api with the championID.
participant 1 : ChampionId (ex 106)
participant 2: ChampionId (ex 142)

And I want to transform this champion Id into the name of it

And this is were I’m stuck, how to tell to the program to Pass the data (Ex 106) in the json file and give me the name associated with it.

Yep, this function should do that, as long as you have the json data with all the champion info that you screenshotted.
If you want just the name, of course, and none of the other data:

function getChampionById (data, id) {
  // This gets you a list of all the keys in champions.data
  let dataKeys = Object.keys(data);
  // Iterate through them, and pull out the one that matches the championId that you want
  for (let key of dataKeys) {
    if (data[key].key == id) {
      return data[key].name;
    }
  }
  // Return something if that number doesn't exist.
  return {error: "Champion not found"}
}

let championName = getChampionById(champions.data, championId)

Edit: I just saw in your code where I think you need this info:

this.setState({participantchamp1: getChampionById(champions.data, res.data.participants[0].championId)});
1 Like

Ok!
After decomposing it, I totally understand what it does and how (Seriously a big thanks on that I was stuck during the day on it :(, I hope I’ll be like people like you later, It’s really frustrating to like, dont know what to do…)
I understand when I saw the code and I know how to do after but I seriously want to learn by my self… uh (I programming since 7 month now … )

this.setState({participantchamp1: getChampionById(champions.data, res.data.participants[0].championId)});

He can’t find champions.data but I declared it in my constructor it’s really weird… I’m on this !

Again a big thanks for your help, really appreciated

And problem solved ! ( Since a lot of time but wanted to write it :D)
just needed to add: this.state.champions

So it will render like this :

this.setState({participantchamp9: getChampionById(this.state.champions,res.data.participants[8].championId)});

So problem solved, thanks a lot man!