0

I have a user_id on my state, it's looks as :

this.state ={id_user:''}

I want to get this id_user from another component, I develop it like that :

handleAjouter = (id_user) => {
    this.setState({
      openPopupAjout: true,
      id_user: id_user
    });
    console.log(id_user, this.state.id_user)
  }

When I run it, I get on the console :

  • id_user: 1258

  • this.state.id_user: it's empty value

But when I change the method handleAjouter to this :

handleAjouter = (id_user) => {
    this.state.id_user = id_user;
    this.setState({
      openPopupAjout: true
    });
    console.log(id_user, this.state.id_user)
  }

I get on the console :

  • id_user: 1258

  • this.state.id_user: 1258

But, I get also Do not mutate state directly. Use setState()

How can I fix it ?

Ichrak Mansour
  • 1,850
  • 11
  • 34
  • 61
  • 1
    `setState` maybe asynchronous. It is not immediately updated after `this.setState`. Pass a callback as second argument and log in that. `this.setState({ openPopupAjout: true, id_user: id_user },() => console.log(this.state.id_user));` – Maheer Ali May 22 '19 at 08:34
  • 1
    setState is asynchronous, and takes an optional callback – jujule May 22 '19 at 08:34
  • @MaheerAli thank you, it works well, you can add it as a answer. – Ichrak Mansour May 22 '19 at 08:37
  • 1
    @CodeLover Glad to know it helped. There is not point to answer the question if duplicate or comment solved your problem. If you have any other problem feel free to ask – Maheer Ali May 22 '19 at 08:38
  • @MaheerAli How can I change the state of table looks as : `this.state.tranches[0].end = end;` – Ichrak Mansour May 22 '19 at 08:45
  • 1
    @CodeLover Try `this.setState({tranches:[{end},...this.state.tranches]})` – Maheer Ali May 22 '19 at 08:48

0 Answers0