skip to Main Content

Here i have a fuction that update the data

async function update() {
      try {
        const res = await axios.post('update', { data: '123' })

       //This response may be delayed
        navigate(previousScreen)

      } catch (error) {
        //handle error
      }
    }

Everything works as expected, but the problem is while updating, if i click to other page it goes to the other screen. Then once the update api promise is resolved, then again navigate() is called which is below await.

Sometime while updating if i click logout, it logout and again it navigate.

Is there is any way to stop all awaiting queues?

2

Answers


  1. Maybe you should check if user is still on the same page before navigating:

    async function update() {
      try {
        const pathBeforeRequest = window.location.pathname;
        const res = await axios.post("update", { data: "123" });
    
        if (pathBeforeRequest === window.location.pathname) {
          //This response may be delayed
          navigate(previousScreen);
        }
      } catch (error) {
        //handle error
      }
    }
    
    Login or Signup to reply.
  2. You cannot stop a Promise once initiated. However, you can prevent the execution of the navigate statement below the await statement when a user has already navigated.

    Step 1: Setup a flag to track navigation. If a user has not navigated yet and the promise resolves, let the navigate(previousScreen) execute. If a user has already navigated, skip the execution.

    let hasUserNavigated = false;
    
    async function update() {
          try {
            const res = await axios.post('update', { data: '123' })
            
           if(!hasUserNavigated){
            navigate(previousScreen)
            }
          } catch (error) {
            //handle error
          }
        }
    

    Step 2:
    Somewhere else in your code, when you navigate, set the flag to true:

    hasUserNavigated = true;
    

    Example, let’s say we want to navigate to some page after a user clicks on logout.

    const handleLogout = () => {
      hasUserNavigated = true;
    
      //navigate users to some page that you want
    }
    

    Inside your return portion of your component, set up a button to logout and navigate users:

    <button 
      onClick={() => handleLogout()}
    >
     logout
    </button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search