Home > OS >  State in react is behind by one click?
State in react is behind by one click?

Time:07-08

Hi guys I was stuck on a problem with state being behind a click. I'm creating an input where users can type the name of the item they want and the handleChange function would filter the original items array for titles that match whatever is in the input value. I searched up a couple stack overflow questions that were similar to this problem and they suggested console.logging in useEffects but when I do that, it's still one click behind. Any suggestions?

the functionality:

 const handleChange = (e) => {
    const results = []
    setValue(e.target.value)

    for (let item of items) {
      if (item.includes(value)) {
        results.push(item)
      }
    }
    setNewItems(results)
  }


  useEffect(() => {
    console.log(newItems)
  }, [newItems])

the component:

<input
   onChange={handleChange}
   value={value}
/>

CodePudding user response:

Everything is good except the fact that the code tries to access value as soon as it is set. React state updates are batched and both setValue and setItems will be batched and set the state together.

The correct way to access the latest value of value here would be:

if (item.includes(e.target.value))

CodePudding user response:

State assigning is asynchronous, meaning that rendering often doesn't line up with assignments.

You might find some answers here.

  • Related