forked from ADORSYS-GIS/e2e-banking-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: updated the logic in the usestorage.ts
- Loading branch information
1 parent
e5aff4c
commit 695395a
Showing
1 changed file
with
12 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} |