1
onSelectedRow(user, clickEvent){
     const state = this.state;
    this.state['userId'] = clickEvent.target.getAttribute(user['mta:UserId']);
    this.setState(state);
    console.log(user['mta:UserId']);
    console.log(this.state);
}

Okay, so when I click a table-cell in my app this function gets called.

The point of it is to take the users UserId and set the state. This UserId is later on passed down to a child component and used to get specific information. The problem is that I get the correct data in the first console.log but when I then log this.

state the userId is still null for some reason. Anyone had similiar problems?

Kalariya_M
  • 1,357
  • 12
  • 20
novafluff
  • 891
  • 1
  • 12
  • 30
  • 1
    setState is an async operation, it doesn't immediately update the state of your component – Icepickle Nov 02 '17 at 08:26
  • Have you considered [*reading the documentation*](https://reactjs.org/docs/react-component.html#setstate) ? *"`setState()` does not always immediately update the component. It may batch or defer the update until later. This makes reading `this.state` right after calling `setState()` a potential pitfall."* – Felix Kling Nov 02 '17 at 08:30
  • You should not be mutating the state like above: `const state = this.state; this.state['userId'] = clickEvent.target.getAttribute(user['mta:UserId']);` Read here: https://reactjs.org/docs/optimizing-performance.html#the-power-of-not-mutating-data – Naisheel Verdhan Nov 02 '17 at 08:32

1 Answers1

1

It's most probably because you're not updating the const state, but instead trying to mutate the state itself. Also, you don't have to make a copy of a state. You can update just the field you want to update like this:

onSelectedRow(user, clickEvent) {
    this.setState({
        userId: clickEvent.target.getAttribute(user['mta:UserId'])
    }, () => { console.log(this.state.userId) });
    console.log(user['mta:UserId']);
}

Also, your console.log won't read immediate change in the state as setState is an async action.

If you really want to read it you can pass the callback to the setState which fill fire right after the state is updated, or use React's lifecycle method componentDidUpdate().