Skip to content

Commit

Permalink
refactor: refactor the way event listeners are removed on unmount
Browse files Browse the repository at this point in the history
refactor: refactor the way event listeners are removed on unmount
  • Loading branch information
michal-weglarz committed Jul 12, 2024
1 parent e529bf5 commit c9f45b2
Showing 1 changed file with 8 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { browser } from "$lib/internal/utils/browser.js";
import { addEventListener } from "$lib/internal/utils/event.js";
import { Previous } from "$lib/utilities/index.js";
import { browser } from "$app/environment";

/**
* @desc The `NetworkInformation` interface of the Network Information API
Expand Down Expand Up @@ -86,6 +86,7 @@ interface NetworkStatus {
* @returns null if the function is not run in the browser
*/
export function useNetworkStatus() {
console.log("browser", browser);
if (!browser) {
return {
get current() {
Expand Down Expand Up @@ -119,18 +120,18 @@ export function useNetworkStatus() {
};

$effect(() => {
const callbacks: VoidFunction[] = [];

// The connection event handler also manages online and offline states.
if (connection) {
addEventListener(connection, "change", handleStatusChange, { passive: true });
callbacks.push(addEventListener(connection, "change", handleStatusChange, { passive: true }));
} else {
addEventListener(window, "online", handleStatusChange, { passive: true });
addEventListener(window, "offline", handleStatusChange, { passive: true });
callbacks.push(addEventListener(window, "online", handleStatusChange, { passive: true }));
callbacks.push(addEventListener(window, "offline", handleStatusChange, { passive: true }));
}

return () => {
window.removeEventListener("online", handleStatusChange);
window.removeEventListener("online", handleStatusChange);
connection?.removeEventListener("change", handleStatusChange);
callbacks.forEach((c) => c());
};
});

Expand Down

0 comments on commit c9f45b2

Please sign in to comment.