Skip to content

Commit

Permalink
fix: updated the logic in the usestorage.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
AssahBismarkabah committed Mar 19, 2024
1 parent e5aff4c commit 695395a
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions power-pay-frontend/src/hooks/useStorage.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,33 @@

import { useContext, useEffect, useState } from 'react';
import StorageContext, { StorageContextData } from './StorageContext';

// UseStorageProps<T>: An interface defining the props for the useStorage hook
interface UseStorageProps<T> {
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<T = string>: A generic function that accepts a UseStorageProps<T> object.
export function useStorage<T = string>({ key, initialValue }: UseStorageProps<T>): [T, React.Dispatch<React.SetStateAction<T>>, () => void] {
export function useStorage<T = string>({ key, initialValue }: UseStorageProps<T>): [T | undefined, React.Dispatch<React.SetStateAction<T | undefined>>, () => void] {
const { item, setItem, removeItem } = useContext(StorageContext) as StorageContextData<T>;

// 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<T | undefined>(() => {
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];
}

0 comments on commit 695395a

Please sign in to comment.