Skip to content
Advertisement

Why does my state variable in ReactJS not render and why is it undefined?

Beginner to React and JavaScript, so forgive me if this is a simple fix.

I’m fetching data from a server and intend on parsing the response and storing elements of the response in an array which is a state variable, as I want to use variations in the state to update the page accordingly.

The issue I am having is that while using fetch(), I am able to retrieve the data from the server, but apparently I am unable to use setState() properly to assign the data to the variable. I’ve read that setState() is asynchronous, so your state variable might not be updated right away, and in that case I wonder if I can render the application whenever my state variable (array) is updated.

Below is my code:

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

class App extends Component{
  constructor(props)  {
    super(props);
    this.state = { 
      apiResponse: []
    }; 
    this.getData = this.getData.bind(this);
  }
  componentDidMount() {
    this.getData();
  }

  getData = () => {
    fetch('http://localhost:5000')
      .then(results => results.json())
      .then(console.log)
      .then(results => this.setState({apiResponse: results}, () => {
        console.log('data in state', this.state.apiResponse)
      }))
      .catch(err => console.error(err));
  }
  render()  {
    return (
      <div className="App">
        <h1>Display</h1>
        <h1>{this.state.apiResponse}</h1>
        <h1>Does this work?</h1>
      </div>
    );
  }
}

export default App;

The first console.log that I run after fetch returns the appropriate JSON object, however the next console.log after returns an undefined, and {this.state.apiResponse} does not render anything.

Advertisement

Answer

You are handling the json object with then method but then you don’t return something in order for the next then to have as input.

If you remove this line

.then(console.log)

then it should work.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement