Home > Software design >  How to unsubscribe with useEffect with a function return from a promise?
How to unsubscribe with useEffect with a function return from a promise?

Time:10-24

I call a promise, it returns a unsubscribe function. How do I unsubscribe it with the return function in useEffect?

useEffect(()=>{
   let unSub = ()=>{}   

   async function run(){
        unSub = await promise();
   }

   run();

   
   return unSub
})

Thinking something like this, do not know if it is the correct way, what's the react way of doing it?

CodePudding user response:

// on component mount
useEffect(() => {
    // do some stuff ie. subscribe

    // on component unmount
    return () => {
       // do some stuff ie. unsubscribe
    }
}, [/* dependencies */])

CodePudding user response:

I don't think there's a specific well-known practice for your specific case. Traditional React way of unsubscribing from async actions is using a boolean in the main body of the useEffect, and resetting it in the cleanup.

If you're using the fetch api, the AbortController api can cancel requests. If you're using axios, there are things called cancelTokens that can cancel requests.

Perhaps this can be a solution:

useEffect(()=>{
    let unSub = ()=>{};
    let isMounted   = true;
    let newUnSubSet = false;
    async function run(){
         unSub = await promise();
         newUnSubSet = true;
    }
     
    run();
     
    
    return () => {
        if (newUnSubSet) {
            unSub();
        }
        newUnSubSet = false;
        isMounted = false;
    }
})
  • Related