NathanB
NathanB

Reputation: 3

React state is not being updated by my call to the API

I'm new to React but looking at similar questions and answers, I think this should be working. but it's just returning null. if I set the default state to an empty array it sill just returns and empty array. also i'm getting no errors and the fetch IS being called.

import React, { Component } from     "react";
import "./App.css";
import Header from "./Header";
import BreweriesContainer from "./BreweriesContainer";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      names: null
    };
  }

  componentDidMount() {
    fetch("https:api.openbrewerydb.org/breweries?by_state=Colorado")
      .then(response => response.json())
      .then(jsonData => {
        this.setState({ names: jsonData.name });
        console.log(this.state.names);
      });
  }

  render() {
    return (
      <div className="App">
    <Header />
    <p>{this.state.names}</p>
    <BreweriesContainer />
  </div>
    );
  }
}

export default App;

Upvotes: 0

Views: 89

Answers (5)

Ryan Wolton
Ryan Wolton

Reputation: 71

Diogo has your answer, jsonData is an array so you need to access it with jsonData[0]

Upvotes: 0

Diogo Peres
Diogo Peres

Reputation: 1372

Your jsonData.name will not work because the request is return an array with multiple values with a key called name. So jsonData.name will be undefined. Try jsonData[0].name.

If you want all the names use a map function like this:

this.setState({ names: e.map( (object) => object.name ) });

Also, you should do the console log like @Kishan said:

this.setState({ names: jsonData.name },() =>{
        console.log(this.state.names);
});

Upvotes: 2

Kevin Struillou
Kevin Struillou

Reputation: 914

Is it not just a typo?

this.setState({ names: jsonData.name });

should perhaps be

this.setState({ names: jsonData.names });

Upvotes: 0

Sarath P S
Sarath P S

Reputation: 141

console.log immediately after a setState call, won't work as expected because setState updates the state asynchronously and the console.log statement won't wait for the setState to finish before printing out the previous/default value

Upvotes: 0

Kishan Jaiswal
Kishan Jaiswal

Reputation: 664

 this.setState({ names: jsonData.name },() =>{
        console.log(this.state.names);
});

console in setstate callback you will get updated state or console in render function

Upvotes: 3

Related Questions