mirror of
https://github.com/netbirdio/netbird.git
synced 2026-07-17 12:09:58 +00:00
refetch restrictions on window visibility change
This commit is contained in:
@@ -1,4 +1,12 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { Events } from "@wailsio/runtime";
|
||||
import { Settings as SettingsSvc } from "@bindings/services";
|
||||
import { Restrictions } from "@bindings/services/models.js";
|
||||
@@ -12,19 +20,19 @@ export const useRestrictions = () => useContext(RestrictionsContext);
|
||||
|
||||
export const RestrictionsProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [restrictions, setRestrictions] = useState<Restrictions>(EMPTY);
|
||||
const mounted = useRef(true);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const r = await SettingsSvc.GetRestrictions();
|
||||
if (mounted.current) setRestrictions(r);
|
||||
} catch (e) {
|
||||
console.error("[RestrictionsContext] refresh failed", e);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const r = await SettingsSvc.GetRestrictions();
|
||||
if (!cancelled) setRestrictions(r);
|
||||
} catch (e) {
|
||||
console.error("[RestrictionsContext] refresh failed", e);
|
||||
}
|
||||
};
|
||||
|
||||
mounted.current = true;
|
||||
refresh();
|
||||
|
||||
const off = Events.On(
|
||||
@@ -33,11 +41,18 @@ export const RestrictionsProvider = ({ children }: { children: ReactNode }) => {
|
||||
if (e.data?.metadata?.type === "config_changed") refresh();
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
off();
|
||||
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === "visible") refresh();
|
||||
};
|
||||
}, []);
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
off();
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, [refresh]);
|
||||
|
||||
return (
|
||||
<RestrictionsContext.Provider value={restrictions}>{children}</RestrictionsContext.Provider>
|
||||
|
||||
Reference in New Issue
Block a user