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
  • Loading branch information
michal-weglarz committed Jul 12, 2024
1 parent e529bf5 commit f72ffda
Show file tree
Hide file tree
Showing 2 changed files with 10 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
2 changes: 2 additions & 0 deletions sites/docs/src/lib/components/demos/use-network-status.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,7 @@
<DemoContainer>
{#if networkStatus.current}
<pre>{JSON.stringify(networkStatus.current, null, 2)}</pre>
{:else}
<p>Network Status is currently not available on your device</p>
{/if}
</DemoContainer>

0 comments on commit f72ffda

Please sign in to comment.