S
S
semki0962020-02-20 12:52:35
React
semki096, 2020-02-20 12:52:35

Why is the updated state not visible in the console?

Why does console.log componentDidMoungive updated data inside, but console.logat the end it gives 122? I don’t understand why it gives out old, not updated data, because it is triggered by the .onmessage event every 2 seconds. I will be grateful for help.

constructor(props) {
  super(props);
  this.state = { messages: [122] };
};

componentDidMount() {
  this.connection = new WebSocket('ws://reactchart:8080');
  this.connection.onmessage = responce => { 
    this.setState({
      messages : responce.data
    });
    console.log(this.state.messages);
};
this.connection.onmessage = responce => console.log(this.state.messages);
....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
real2210, 2020-02-22
@semki096

setState asynchronous method, use a callback to have actual data after the state changes

this.setState({
      messages : responce.data
    }, () =>  console.log(this.state.messages));
  ;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question