Skip to content

Commit

Permalink
fix: updated usestorage
Browse files Browse the repository at this point in the history
  • Loading branch information
AssahBismarkabah committed Mar 17, 2024
1 parent d3d1db1 commit 2f66278
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions power-pay-frontend/src/hooks/useStorage.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,33 @@
//useState and useEffect hooks from React
import { useState } from 'react';

//UseStorageProps<T>: An interface defining the props for the useStorage hook
// UseStorageProps<T>: An interface defining the props for the useStorage hook
interface UseStorageProps<T> {
initialValue?: T | undefined;
key: string; // the key to use for storing and retrieving the value from local storage
initialValue?: T | undefined; // the initial value to use for the state variable
}

//useStorage<T = string>: A generic function that accepts a UseStorageProps<T> object.
// useStorage<T = string>: A generic function that accepts a UseStorageProps<T> object.
export function useStorage<T = string>(props: UseStorageProps<T>): [T, React.Dispatch<React.SetStateAction<T>>, () => void] {
const { key, initialValue } = props;

export function useStorage<T = string>(props: UseStorageProps<T>): [T, React.Dispatch<React.SetStateAction<T>> , () => void] {
// storedValue: A state variable that stores the value retrieved from the localStorage using the provided key
const [storedValue, setStoredValue] = useState<T>(() => {
// Retrieve the value from local storage using the provided key
const valueInLocalStorage = localStorage.getItem(key);

const { initialValue } = props;

//storedValue: A state variable that stores the value retrieved from the localStorage using the provided key

const [storedValue, setStoredValue] = useState<T>(initialValue!);
;

//adding a newfunction removeValue to remove the stored value from the localstorage and set it to its initial state
// If the value exists, parse it from JSON and return it. Otherwise, return the initial value.
return valueInLocalStorage ? JSON.parse(valueInLocalStorage) : initialValue!;
});

// adding a new function removeValue to remove the stored value from the localstorage and set it to its initial state
const removeValue = () => {
// Set the storedValue to the initial value
setStoredValue(initialValue!);

// Remove the value from local storage using the provided key
localStorage.removeItem(key);
};

return [storedValue, setStoredValue , removeValue];
}
// Return the storedValue, setStoredValue function, and removeValue function as an array
return [storedValue, setStoredValue, removeValue];
}

0 comments on commit 2f66278

Please sign in to comment.