0

My column where I added OnClick function when I click

<Col onClick={()=>optionSelected("usermanagement")}
            className={
              currentSelection === "usermanagement" ? "selectedOp" : "option"
            }
            tabIndex="-1"
            style={{ cursor: "pointer" }}
          >

Well, This may look dumb way to access the route but I want this for some other purpose .

 function optionSelected(optionName) {
    if (optionName === "usermanagement") {
      setCurrentSelection("usermanagement");
      history.push("/" + currentSelection);
    }
    if (optionName === "foodcatalog") {
      setCurrentSelection("foodcatalog");
      history.push("/" + currentSelection);
    }
    if (optionName === "promotions") {
      setCurrentSelection("promotions");
      history.push("/" + currentSelection);
    }
    if (optionName === "tickets") {
      setCurrentSelection("tickets");
      history.push("/" + currentSelection);
    }
    if (optionName === "reports") {
      setCurrentSelection("reports");
      history.push("/" + currentSelection);
    }
   }

Why I can access the page (history push) only on the second click ?

1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Sep 8, 2021 at 9:22

1 Answer 1

1

Because react bundles setState calls together asynchronously. So by the time the code reaches history.push, currentlySelection hasn't changed yet.

change history.push("/" + currentSelection); to history.push("/" + "reports"); (or whatever route you are trying to get to)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot... Thought the dynamic way would be a pro way to call the route.. lol !
if you want to do it like this then you can put history.push("/" + currentSelection); in a useEffect and have the state as dependency and it'll change route once state updates. or write a function that does the same code and just call it with a different arg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.