0

I'm attempting to pull data from the array below. My code is below my console.log. What am I doing wrong? Nothing is rendering when I attempt to pull the data.

(356) […]
​
[0…99]
0: Object { TournamentID: 405, Name: "The Presidents Cup", StartDate: "2021-09-30T00:00:00", … }​​
1: Object { TournamentID: 453, Name: "Tour Championship", StartDate: "2021-09-02T00:00:00", … }​​
2: Object { TournamentID: 452, Name: "BMW Championship", StartDate: "2021-08-26T00:00:00", … }
​​

Below is the code I'm using to pull the data.


function App() {
  const [data, setData] = useState([])

  useEffect(()=>{
    axios
    .get('https://api.sportsdata.io/golf/v2/json/Tournaments?key=72259e02756442d38c6b837dd8625e4f')
    .then((res)=> {
      
     console.log(res.data)
     setData(res.data)
})

  },[])

  return (
    
    <div className="App">
        
        <div className='container'>
        
        <h1>{data.Name}</h1>
        

      </div>
      
    </div>
    
  );
}

export default App;
1
  • 1
    You are using data is an object, but it seems to be an array, you should use map to iterate over the elements. In this case data.Name is undefined Commented Dec 25, 2020 at 21:40

1 Answer 1

3

You need to map over the array of data with something like this:

return (
  <div className="App">
    <div className='container'>
      {data.map(item => <h1 key={item.TournamentID}>{item.Name}</h1>)}
    </div>
  </div>
);

You also need the key attribute.

Sign up to request clarification or add additional context in comments.

2 Comments

Single letter variables is not the best approach, even here. Better change it to item => or something.
I agree. I'll update the answer. This stems from the use of generic terms such as data - if this was my code, I'd suggest changing data to items (plural indicates an array or collection) and the d would become item.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.