From 695395a331b31acf3ca8196909c8c901c498d380 Mon Sep 17 00:00:00 2001 From: AssahBismarkabah Date: Tue, 19 Mar 2024 18:33:07 +0100 Subject: [PATCH] fix: updated the logic in the usestorage.ts --- power-pay-frontend/src/hooks/useStorage.ts | 26 ++++++++++------------ 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/power-pay-frontend/src/hooks/useStorage.ts b/power-pay-frontend/src/hooks/useStorage.ts index 9f7dceef..ddea890c 100644 --- a/power-pay-frontend/src/hooks/useStorage.ts +++ b/power-pay-frontend/src/hooks/useStorage.ts @@ -1,35 +1,33 @@ - import { useContext, useEffect, useState } from 'react'; import StorageContext, { StorageContextData } from './StorageContext'; +// UseStorageProps: An interface defining the props for the useStorage hook interface UseStorageProps { - key: string; - initialValue?: T | undefined; + key: string; // the key to use for storing and retrieving the value from local storage + initialValue?: T; // the initial value to use for the state variable } // useStorage: A generic function that accepts a UseStorageProps object. -export function useStorage({ key, initialValue }: UseStorageProps): [T, React.Dispatch>, () => void] { +export function useStorage({ key, initialValue }: UseStorageProps): [T | undefined, React.Dispatch>, () => void] { const { item, setItem, removeItem } = useContext(StorageContext) as StorageContextData; - // Initialize the state variable with the initial value or the value from the local storage + // Initialize the state variable with the value from the context or the initial value const [storedValue, setStoredValue] = useState(() => { return item[key] ?? initialValue; }); - // Another useEffect for updating the stored value when the context changes - useEffect(() => { - setStoredValue(item[key] ?? initialValue); - }, [item, key, initialValue]); - + // Update the context when the storedValue changes useEffect(() => { - setItem(key, storedValue!); + if (storedValue !== undefined) { + setItem(key, storedValue); + } }, [key, storedValue, setItem]); - // Remove the item from local storage and set the stored value to undefined + // Clear the item from local storage and reset the stored value const clearItem = () => { removeItem(key); - setStoredValue(undefined) + setStoredValue(initialValue); // Reset stored value to initial value }; - return [storedValue!, setItem, clearItem]; + return [storedValue, setStoredValue, clearItem]; }