0

The following code works:

import React, { Component } from 'react';
import './App.css';

import Menu_dropdown from "./component/menu_dropdown";

class App extends Component {

  constructor() {
    super()
    this.state = {
      races: {}
    }
  }

  componentDidMount(){
    fetch('https://www.dnd5eapi.co/api/races/')
      .then(response=> response.json())
      .then(races => {this.setState({ races : races})});
  }


  render(){
    const { races } = this.state;
    console.log(races['results']);
    return (
    <div className="App">
      <header className="App-header">
        <Menu_dropdown races = {races}/>
      </header>
    </div>
    );
  }
  
}

export default App;

console will output an array of races. However,it gives me "TypeError: Cannot read property '0' of undefined" when I change to this

console.log(races['results'][0]);

why is results not an array? You can view source json here: https://www.dnd5eapi.co/api/races/

DeepDream
  • 3
  • 2
  • How does `races` look like? – Wais Kamal Jun 18 '21 at 18:30
  • I'm surprised `console.log(races['results']);` gives you an output as on the first render `races.results` will be undefined too. – Andy Jun 18 '21 at 18:33
  • Is render waiting for did mount? If not then [this is a dupe](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – mplungjan Jun 18 '21 at 18:36
  • races is {}, after get response from the api, it returns a javascript object with 2 properties: counts and results. – DeepDream Jun 18 '21 at 18:37
  • simply change `console.log(races['results']);` to `console.log(races['results'][0]);` in context you will get the not working code – DeepDream Jun 18 '21 at 18:40
  • Got it, i just reread the question. Working on the solution :)) – GustavMH Jun 18 '21 at 18:41
  • I do not think render is waiting for did mount, because console can output the result of races. I can also access `races[count]` which is 9, and `races[results]` which gives me an array. But if I go `races[results][0]`, I get an error – DeepDream Jun 18 '21 at 18:45

1 Answers1

0

When state is first initialized to { races: {}}, races.results will be undefined and you can't get any elements from undefined.

Simply change the constructor to:

constructor() {
    super()
    this.state = {
      races: {results: []}
    }
  }

This way the component can render an empty array while loading and the fetch results when the fetch call is resolved.

GustavMH
  • 209
  • 2
  • 5