set Value is lagging in reactjs useState hook

Viewed 26
export default function Content(props) {
  const [lookUp, setLookUp] = useState(null);
  return (
    <InputBase
      sx={{ ml: 1, flex: 1 }}
      placeholder="Search links"
      onChange={(e) => {
        //question is on the following two lines of code

        setLookUp(e.target.value);
        console.log(lookUp);
        if (true) {
          props.setLinkList(
            props.LinkList.filter((search) =>
              search.title.toLowerCase().includes(lookUp)
            )
          );
        }
      }}
    />
  );
}

NB: notice the comment of the code. As I've described from the code above, the two lines of code are what I'm asking. eg) if I write "er", it logs "e" to the console. then if "e" character and make it "ert" it console "er" to the console. setLookUp is lagging

I want it to log "er" when I write "er" on my InputBase or Textfield. how can I achieve it.? Anyone with the solution please?

1 Answers

Setting state is asynchronous in React.

If you can use class components, you can use the 2nd argument of setState.

handleChange=(evt)=>{
    this.setState({lookUp: evt.target.value}, ()=> {
        // the 2nd argument of setState is a callback that is called after
        // the state update is over
        console.log(this.state.lookup);
        if(true) {
            this.props.setLinkList(
                this.props.linkList.filter((search) =>
                    search.title.toLowerCase().includes(this.state.lookUp)
                )
            );
        }
    });
}

Or if you have to use function components, you can use useEffect :

useEffect(()=> {
    console.log(lookUp);
    if (true) {
        props.setLinkList(
            props.LinkList.filter((search) =>
                search.title.toLowerCase().includes(lookUp)
            )
        );
    }
}, [lookUp]); // 2nd argument is dependency arry

Since lookUp is a dependency of useEffect it's run every time lookUp is updated.

Related