re: Let's build a search bar in React! VIEW POST

FULL DISCUSSION
 

Thanks for the article.

You addItem/removeItem has a fairly unlikely race condition in it.

You are reading the list from the state, modifying it, then using this.setState. However, this.setState does not update the state immediately.

In theory, addItem could get called twice in quick succession, and you would lose one of the items added. For example with this possible ordering of events:

  • Initial List ["a", "b", "c"]
  • addItem Called with "d", modified list ["a", "b", "c", "d"], setState called
  • addItem called with "e", modified list ["a", "b", "c", "e"], setState called
  • State is updated with ["a", "b", "c", "d"]
  • State is updated with ["a", "b", "c", "e"]

Just something to keep in mind.

 

Interesting. How would you suggest preventing that issue in a project like this?

 

Use call back format for setState.

this.setState(state => {
  const list = state.list;
  /* modify list */;
  return {
    list: modifiedList
  };
});
code of conduct - report abuse