1

I am trying to display the name of each of the teams using the following API:https://www.balldontlie.io/api/v1/teams. I have the following code in my main app.js file:

const result = await Axios('https://www.balldontlie.io/api/v1/teams')
console.log(result.data)
console.log(result.data.data[0])

This is successfully able to fetch the data and the first console line is able to display all data in the console while the second line displays all the information about the first team in the data. In each of the teams data information, they have one attribute that is called 'name' and says the team name. I was wondering on how I will be able to call this. When I have the following code in another file it doesn't display anything on the screen:

{Object.keys(items).map(item => (
            <h1 key={item}>{item.data}</h1>
        ))}

What should I change item.data to be able to properly display the names of all the teams? I could provide more code if needed, but I thought this code would probably do.

3
  • 1
    Providing the response of the API will be helpfull to find the issue Commented Jul 26, 2020 at 0:28
  • Currently, there is no response on the screen, but the response I get on the console is this:balldontlie.io/api/v1/teams. Commented Jul 26, 2020 at 0:29
  • what is items in your code? Commented Jul 26, 2020 at 1:09

5 Answers 5

1

Don't use axios, now JS has a better alternative called fetch. wrap call on a async function. finally destructor the data object. and void installing more things on your node_modules.

What's here ?

  1. Request endpoint using callApi function

  2. Collect only data from all json scope when finish promise.

  3. Loop over each name

const myComponent = () => {
    const names = [];
    const callApi = async () => {
        await fetch('https://www.balldontlie.io/api/v1/teams')
        .then(r => r.json())
        .then(resp => { const { data } = resp; return data; })
        .catch(e => { console.log(e.message); });
    };
    callApi();

    return <>
        {names && names.length > 0
        ? <span>{names.map(({ id, name }) => <h1 key={id}>{name}</h1>)}</span>
        : <span>No rows </span>}
    </>;
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a possible way to use axios to solve this problem?
Yes you can use axios. Just follow the same code sample. fetch and axios follow the same principles :)
0

According to your second block of code, you are trying to access a "data" property of a string, since you are mapping an array of keys of the items.

Effectively:

const item_keys = Object.keys(items);
//if the items is an array, item_keys = ["0","1",...]
//if items is an object, item_keys = ["id","name",...]
const result = item_keys.map(item => (
    <h1 key={item}>{item.data}</h1>
));
//either way, result is an array of <h1>undefined</h1>
//because item is a string

Assuming you defined items as const items = result.data.data (edited), you should be able to display names like this:

{items.map((item, index) => (
    <h1 key={index}>{item.name}</h1>
))}

4 Comments

How would I have to change my code to get the names of the teams?
It still is not working. I tried this approach in just inputting in the console log also and that was causing an error so I don't think this is the correct path.
@goat9009 Mistyped. It should have been const items = result.data.data. Also, if that doesn't work, try to edit your question to add the console error you were talking about
Sorry, I didn't mean an error, I just meant it doesn't display anything when I use the code you recommended which I think probably means it isn't pointing to the proper pathway.
0
const result = await Axios('https://www.balldontlie.io/api/v1/teams')
const data = result.data;

//if you want to display all names
{
    data.map(team => (
        <div>
            <h1 key={`${team.id}`}>{team.name}</h1>
        </div>
    )
}

//if you want to display all fields in each team
{
    data.map(team => (
        <div key={`${team.id}`}>
            {
                Object.keys(team).map((key, keyIndex) => (
                    <h1 key={`k-${team.id}-${keyIndex}`}>{team[`${key}`]}</h1>
                ))
            }
        </div>
    )
}

7 Comments

Using keyIndex as key index is bad practice, can lead to errors.
Oh. But i could pass a unique id as i have done in case of teamId, because there is an id. But what else can i use as a key? I thought it would be better to have index as key than having no key.
In this example you can use either the JSON response ID or create a counter variable from outside map scope. And increment the counter for that variable. because what if you have 2 components that loop over the same main component? both have the same key and will fail.
ohh.. like var incKey = 1; ... <div key={incKey++} />
yes, but the ++ cannot be asigned inside the key because it's ilegal. need to do it on before the return. this is only in case you dont have a unique key comming to your loop.
|
0

Your response is an array

// you need to change this 
Object.keys(items).map(item => (
        <h1 key={item}>{item.data}</h1>
))}
// to this where items = result.data.data
items.map(item => <h1 key={item.id}>{item.city} </h1> 
// to note here item.city need to be a string or number and not an objet
//if your data does not have an Id
items.map((item, index) => <h1 key={index}>{item.city} </h1> 

and in your code this will become somthing like this

return (
   <div>
     {items.map((item, index) => <h1 key={index}>{item.city} </h1>}
   </div>
)

Here an example how the complete code should looks, since you are seeing the response and data in console but not in the UI, it could be a state problem.

const App = () => {
  const [items, setItems] = useState([]);
  useEffect(()=>{
    fetch('https://www.balldontlie.io/api/v1/teams')
    .then(res => res.json())
    .then(res => {
        setItems(res.data);
    })
    .catch(error => { 
    //handle error here
    });
},[])
  return (
    <>
      {items.map(el => <h1 key={el.id}> el.city </h1>}
    </>
  )
}

7 Comments

using index as a key value is a bad practice... can lead to errors
why object key? no need for that.
what objet.key ?
item.city sadly doesn't give the names as I tried to even print this data in the console and it didn't work out, but result.data.data[0] was able to give me the first team on the console and result.data=item in case you were wondering.
this means that items = result.data.data, check the update
|
0

As your data response is an array of objects and your requirement is to display attributes of that data, you can just run a simple loop on data and render items. Below "data" is the response from API

const data = [{"id":"1",name:"Team1"}, {"id":"2",name:"Team2"}]
   
data.map(item => 
   <div>
       <h1 key={id}>{item.name}</h1>
   </div>
);

1 Comment

The data response is from this:balldontlie.io/api/v1/teams. If you copy the link to your search engine then it would give the data I am receiving. When I use this input it leads to a pathway that displays nothing even on the console log.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.