@@ -20,23 +20,30 @@ export function getCookie(cname: string) {
2020 * Detects changes in a given cookie by polling it with the given interval
2121 * @param cookieName The name of the cookie to be checked
2222 * @param interval The interval in which to poll the cookie (given in milliseconds)
23+ * @param delayResponse The delay in milliseconds before signalling that the cookie has changed. Defaults to 0ms (no delay).
2324 * @returns `true` if the cookie has been changed from it's original value, `false` otherwise.
2425 */
25- export const useCookieListener = ( cookieName : string , interval = 2000 ) => {
26+ export const useCookieListener = ( cookieName : string , interval = 2000 , delayResponse = 0 ) => {
2627 const [ cookieValue , setCookieValue ] = useState ( getCookie ( cookieName ) ) ;
2728 const [ cookieChanged , setCookieChanged ] = useState ( false ) ;
2829
2930 useEffect ( ( ) => {
31+ let delayTimeout : ReturnType < typeof setTimeout > | undefined ;
32+
3033 const checkCookie = setInterval ( ( ) => {
3134 const currentCookie = getCookie ( cookieName ) ;
3235 if ( currentCookie !== cookieValue ) {
3336 setCookieValue ( currentCookie ) ;
34- setCookieChanged ( true ) ;
37+ clearTimeout ( delayTimeout ) ;
38+ delayTimeout = setTimeout ( ( ) => setCookieChanged ( true ) , delayResponse ) ;
3539 }
3640 } , interval ) ; // Check every interval
3741
38- return ( ) => clearInterval ( checkCookie ) ;
39- } , [ cookieName , interval ] ) ;
42+ return ( ) => {
43+ clearInterval ( checkCookie ) ;
44+ clearTimeout ( delayTimeout ) ;
45+ } ;
46+ } , [ cookieName , interval , delayResponse ] ) ;
4047
4148 return cookieChanged ;
4249} ;
0 commit comments