DEV Community

Discussion on: Let's build a search bar in React!

Collapse
 
zrbecker profile image
Zachary Becker

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.

Collapse
 
iam_timsmith profile image
Tim Smith

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

Collapse
 
zrbecker profile image
Zachary Becker • Edited

Use call back format for setState.

this.setState(state => {
  const list = state.list;
  /* modify list */;
  return {
    list: modifiedList
  };
});
Enter fullscreen mode Exit fullscreen mode