reactjsaxiosriot-games-apibottleneck

Having trouble saving a list of match data from riot api to a state array


Trying to create a small op.gg like app.

Basically what im trying to do is to find a way of grabbing data from each match and being able to display it. I was able to grab that data and print it to the console but cannot find a way to store into a state array or have an efficient way to update the state array in order to display it in order onto the web.

As you can see, I made an api call to grab a list of match id's which i then use to do another api call grab the data from each one of those matches. I used a bottleneck since the rate limit is 10 request per second.

   loadPlayerMatchData(puuid) {
        var API_KEY = MYRIOTAPIKEY
        const limiter = new Bottleneck({
            minTime:500
        })
        const throttleGetMatchData = limiter.wrap(getMatchesInformation)

        axios.get("https://americas.api.riotgames.com/tft/match/v1/matches/by-puuid/"+puuid+"/ids"+"?api_key=" + API_KEY).then((res) => {
            console.log(res.data)//match IDS

            res.data.map((id)=> {
                  
                throttleGetMatchData(id)//calling function with a bottleneck throttle
            })
        }).catch((errs)=> {
            console.log(err)
        })

        function getMatchesInformation(id) {
            axios.get("https://americas.api.riotgames.com/tft/match/v1/matches/"+ id +"?api_key=" + API_KEY).then((res) => {
                console.log(res.data)

                //PROBLEM STARTS HERE!!!!
                
                //******this.state.playerMatchInfo.push(res.data) <--- wont let me do this
               //return(res.data)<---- returns unfulfilled promises



            }).catch((err)=> {
                console.log(err)
            })
           
        }
        
    }

You can see that I'm doing all of this inside a react hook. I cant seem to use state arrays either inside a local function (getMatchesInformation) within the hook.

In conclusion im trying to see if i can pull off somehow saving data into an array like this.state.matches = []

Would using redux help solve this issue?


Solution

  • Your data needs time to come back. You can use async-await to solve the problem

    async function getMatchesInformation(id) {
        const res = await axios.get("https://americas.api.riotgames.com/tft/match/v1/matches/"+ id +"?api_key=" + API_KEY)
        this.state.playerMatchInfo.push(res.data)
       
    }