0

my page state doesn't change on first click. i set useState name redirect, to change page state to boolean value, but on first click it doesn't work. if you go back to page from second click it's ok and it works.

const [redirect, setRedirect] = useState();
 const PluNum = (plu) => {
    const product = posts.find(
      (item) => item.plu.toString() === plu.toString()
    );
    if (product) {
      setRedirect(true);   // here on first click state don't change to true
      console.log(redirect)
      const prevproduct = items.find((item) => item.id === product.id);
      setSelectedpr( product  );
      setNum("")
  }
  
  else if(!product){
    setRedirect(false);  // here on first click state don't change to false
    console.log(redirect);
    toast.error("plu is wrong");
}
}

i put this condition in html code

    {redirect ? 
        <Link to="/pluitem" className="digit" onClick={()=>PluNum(num)}>submit</Link> 
        : 
          <div className="digit" onClick={()=>PluNum(num)}>submit</div>
        }

i test code below but it did not work too

setRedirect((prevState) => [prevState, true]);
setRedirect((prevState) => [...prevState, true]);
alireza
  • 83
  • 2
  • 9
  • Does this answer your question? [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) – Iain Shelvington Aug 23 '22 at 06:43
  • no it does not works – alireza Aug 23 '22 at 07:14

0 Answers0