A question about setState order of operation

Dear friends, this block of codes was in the “answer” to the React challenge. submitMessage() is supposed to clear the input field and send what was typed in into “messages”.

However, if in setState, we first clear “input” to an empty string, wouldn’t the “this.state.input” in the next line be an empty string too? (Instead of what was previously typed in).

If anyone has an answer to this question, I would really appreciate it!

input: ‘’,
messages: […this.state.messages, this.state.input]

I assume it is this challenge you are referring to?

Manage State Locally First

this.state.input will not be set to an empty string until after setState has run. So you can set input to an empty string and still use the current value inside the setState. Only after setState has run and the state has updated is this.state.input an empty string.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.