简体   繁体   中英

How to display data from an api call that returns an object instead of an array

http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion.json

This is the api im attempting to work with. For some reason when i go to map over it to pull data from it and display the data it says champions.map is not a function. (I am guessing it says this because i cant iterate over an object using .map. So i tried using Object.keys(champions) and i still cant really get it to do what i want it to do.

I feel im missing something super easy as its been quite some time since i have made any api calls.

Here is my code.

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import ChampionContainer from "./ChampionContainer";
// import { Link } from 'react-router-dom';


const ChampionList = () => {
    const [ champions, setChampions ] = useState([])
    console.log("This is our state",champions)

    useEffect(() => {
            const url = "http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion.json";
            axios.get(url)
            .then(response => {
                setChampions(response.data.data);
            })
            .catch(error => {
                console.log("server Error", error)
            })
    }, [champions]);




    return (
        // Object.keys(a).map(function(keyName, keyIndex) {
        //     // use keyName to get current key's name
        //     // and a[keyName] to get its value
        //   })
        <div>
            {Object.keys(champions).map((key) => {
                return (<div key={key}>{champions[key]}</div>)
            })}
            {/* {champions.map((champion) => (
                <ChampionContainer key={champion.id} champion={champion}/>
            ))} */}
        </div>

    );
}


export default ChampionList;

Thanks in advance for the help.

You are right, you're first attempt at doing .map() on champions wont work as it is not an array, it's an object.

You're second attempt is closer, though when you do -

champions[key]

this returns one of your champion objects. You just need to access the property you want from that object, eg

champions[key].name - to get the name of the champion eg Aatrox

You have a infinite loop there. In useEffect pass champions as a parameter, when it changes you excecute useEffect, but in there you setChampions, then champions changes an useEffect is running again. infinite loop as a result.

You debug your program to make sure that respomse.data.data have the information you need?

In setChampions function is better to use setChampions(current => current + newData); this is an object, so you should use spread operator to map onto a new object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM