0
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?

Felix
  • 2,531
  • 14
  • 25
  • 1
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Henry Woody Sep 17 '22 at 08:42
  • It's not available immediately after setting the state ... It should call the component again with new props ... You can keep the log outside and check ... You can read this - [for more info](https://gist.github.com/bpas247/e177a772b293025e5324219d231cf32c) – KcH Sep 17 '22 at 09:04

1 Answers1

0

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.

Nice Books
  • 1,675
  • 2
  • 17
  • 21