From 2fdf7549cf72fb42b83a867633975b1eff818cc5 Mon Sep 17 00:00:00 2001 From: MohamedBassem Date: Sun, 9 Mar 2025 21:09:17 +0000 Subject: fix(extension): Fix extension setting hook not firing on setting change. #10 --- apps/browser-extension/src/utils/settings.ts | 45 ++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 9 deletions(-) (limited to 'apps/browser-extension/src/utils') diff --git a/apps/browser-extension/src/utils/settings.ts b/apps/browser-extension/src/utils/settings.ts index 76ff0f61..6d51acde 100644 --- a/apps/browser-extension/src/utils/settings.ts +++ b/apps/browser-extension/src/utils/settings.ts @@ -1,4 +1,4 @@ -import { useChromeStorageSync } from "use-chrome-storage"; +import React from "react"; export interface Settings { apiKey: string; @@ -6,20 +6,47 @@ export interface Settings { address: string; } +const STORAGE = chrome.storage.sync; + export default function usePluginSettings() { - const [settings, setSettings, _1, _2, isInit] = useChromeStorageSync( - "settings", - { - apiKey: "", - address: "", - } as Settings, - ); + const [settings, setSettingsInternal] = React.useState({ + apiKey: "", + address: "", + }); + + const [isInit, setIsInit] = React.useState(false); + + React.useEffect(() => { + if (!isInit) { + getPluginSettings().then((settings) => { + setSettingsInternal(settings); + setIsInit(true); + }); + } + const onChange = ( + changes: Record, + ) => { + if (changes.settings === undefined) { + return; + } + setSettingsInternal(changes.settings.newValue as Settings); + }; + STORAGE.onChanged.addListener(onChange); + return () => { + STORAGE.onChanged.removeListener(onChange); + }; + }, []); + + const setSettings = async (s: (_: Settings) => Settings) => { + const newVal = s(settings); + await STORAGE.set({ settings: newVal }); + }; return { settings, setSettings, isPending: isInit }; } export async function getPluginSettings() { - return (await chrome.storage.sync.get("settings")).settings as Settings; + return (await STORAGE.get("settings")).settings as Settings; } export function subscribeToSettingsChanges( -- cgit v1.2.3-70-g09d2