skip to Main Content

Inside useEffect , I am calling window.location.replace
and once that completes , I need to fetch a value from cookie

I have used await , but didn’t worked

2

Answers


  1. There’s no way to do that.

    When window.location.replace completes, the rest of that function will not run since it’s been unloaded, as you’ve navigated elsewhere.

    Login or Signup to reply.
  2. You can not do it directly on the page where you call window.location.replace , but if you have a control over who calling it and you navigating to the same app, you can use a trick:

    • put a flag with the date to SessionStorage right before calling window.location.replace
    • on component/page load read this flag from SessionStorage and immediatly clear it if it present.
    • Now you have it, if flag is present than you’re here because page has been replaced and you can do whatever you need. You can use date part for extra safety, to make sure that replace happened not long ago.
    const onReplace = () => {
      sessionStorage.setItem(
        "page-replaced", 
         JSON.stringify({ date: new Date().getTime() })
      );
      window.location.replace(...)
    }
    
    ... 
    // somwhere in the component
    useEffect(() => {
      const data = sessionStorage.getItem("page-replaced");
      if (data) {
        sessionStorage.removeItem("page-replaced"); 
        // your logic here
      }
    }, [])
    
    // Alternative version with extra step
    useEffect(() => {
      const str = sessionStorage.getItem("page-replaced");
      if (str) {
        sessionStorage.removeItem("page-replaced");
        const data = JSON.parse(data);
        const currentTime = new Date().getTime()
        if (data.date && (currentTime - date.date) < 5000) {
           // your logic here
        }
      }
    }, [])
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search