DEV Community

Zakaria EL AISSAOUI
Zakaria EL AISSAOUI

Posted on

𝗔𝗯𝗼𝗿𝘁𝗶𝗻𝗴 𝗼𝗻𝗴𝗼𝗶𝗻𝗴 𝗮𝗰𝘁𝗶𝘃𝗶𝘁𝗶𝗲𝘀 𝘂𝘀𝗶𝗻𝗴 𝘁𝗵𝗲 𝗔𝗯𝗼𝗿𝘁𝗖𝗼𝗻𝘁𝗿𝗼𝗹𝗹𝗲𝗿 𝗶𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲.

𝗔𝗯𝗼𝗿𝘁𝗶𝗻𝗴 𝗼𝗻𝗴𝗼𝗶𝗻𝗴 𝗮𝗰𝘁𝗶𝘃𝗶𝘁𝗶𝗲𝘀 𝘂𝘀𝗶𝗻𝗴 𝘁𝗵𝗲 𝗔𝗯𝗼𝗿𝘁𝗖𝗼𝗻𝘁𝗿𝗼𝗹𝗹𝗲𝗿 𝗶𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲.

The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a fetch request) and abort it if required via an AbortController object.

𝗔. 𝗔𝘀𝘆𝗻𝗰 𝘄𝗼𝗿𝗸 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁:
Let's take the example of data fetching placed inside a useEffect hook.
If this effect doesn't finish before it's fired again (re-render), we may have two requests running in parallel.
To make things better, we can create an AbortController instance that will be aborted whenever the next effect runs.
𝘞𝘩𝘦𝘯 𝘢𝘣𝘰𝘳𝘵() 𝘪𝘴 𝘤𝘢𝘭𝘭𝘦𝘥, 𝘵𝘩𝘦 𝘧𝘦𝘵𝘤𝘩() 𝘱𝘳𝘰𝘮𝘪𝘴𝘦 𝘳𝘦𝘫𝘦𝘤𝘵𝘴 𝘸𝘪𝘵𝘩 𝘋𝘖𝘔𝘌𝘹𝘤𝘦𝘱𝘵𝘪𝘰𝘯 𝘯𝘢𝘮𝘦𝘥 𝘈𝘣𝘰𝘳𝘵𝘌𝘳𝘳𝘰𝘳.

𝗕. 𝗥𝗲𝗺𝗼𝘃𝗶𝗻𝗴 𝗘𝘃𝗲𝗻𝘁 𝗛𝗮𝗻𝗱𝗹𝗲𝗿𝘀:
To remove an event handler, you have to keep hold of the original reference.
Using AbortSignal, you can get the signal to remove it for you.

Promise-based APIs wishing to support aborting can accept an AbortSignal object, and use its state to determine how to proceed (https://bit.ly/3HB3hjQ).

code snippet

Top comments (0)