0

I have the below component and I have set the initial state as users:null then I am passing the state to my componentDidMount() as below code

    import React, { Component } from "react";

export default class Users extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: null
    };
  }
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((data) =>
        this.setState({
          users: data
        })
      );
    console.log(this.state.users);
  }
  render() {
    return (
      <div>
        <h1>Users</h1>
      </div>
    );
  }
}

From the above component I am getting a null in the console. Can I know where it went wrong newbie to reactjs

Thanks in advance

hotebi
  • 1
  • `fetch` is asynchronous, `componentDidMount` is synchronous, and you're using a Promise chain. You are logging the initial state because the state update hasn't happened yet. Log state updates in the `componentDidUpdate` lifecycle method. – Drew Reese Aug 31 '21 at 06:24

2 Answers2

0

setState is an asynchronous function that's why you are not able to see data.

you can use setState call back like this then you can see your data.

this.setState({
    users: data
},()=> {
    console.log(this.state.users);
})
Sanat Gupta
  • 1,086
  • 1
  • 10
  • 16
0

The console.log doesn't see the state, because it is asynchronously updated.

Use the callback of setState

componentDidMount() {
  fetch("https://jsonplaceholder.typicode.com/users")
    .then((response) => response.json())
    .then((data) =>
      this.setState({
        users: data
      }, () => {
         console.log(this.state.users);

  })
    );
}

Here is a working example:

class Users extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: []
    };
  }
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((data) =>
        this.setState(
          {
            users: data
          },
          () => {
            console.log(this.state.users);
          }
        )
      );
  }
  render() {
    const userCount = this.state.users.length;
    return (
      <div>
        <h1>Users {userCount}</h1>
      </div>
    );
  }
}

ReactDOM.render(<Users />, document.getElementById("root"));
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
René Link
  • 48,224
  • 13
  • 108
  • 140