Skip to content

Commit

Permalink
fix: updated usestorage.ts -> hook does not interact with the storage
Browse files Browse the repository at this point in the history
  • Loading branch information
AssahBismarkabah committed Mar 12, 2024
1 parent 48933b5 commit 6cc7740
Showing 1 changed file with 5 additions and 14 deletions.
19 changes: 5 additions & 14 deletions power-pay-frontend/src/hooks/useStorage.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@
//useState and useEffect hooks from React
import { useEffect, useState } from 'react';
import { useState } from 'react';

//UseStorageProps<T>: An interface defining the props for the useStorage hook
interface UseStorageProps<T> {
key: string;
initialValue?: T | undefined ;
initialValue?: T ;
}

//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;
const { initialValue } = props;

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

const [storedValue, setStoredValue] = useState<T>(() => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue
});

//runs when the storedValue changes. It updates the localStorage
useEffect(() => {
localStorage.setItem(key, JSON.stringify(storedValue));
}, [key, storedValue]);
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

const removeValue = () => {
localStorage.removeItem(key);
setStoredValue(initialValue!);
};

Expand Down

0 comments on commit 6cc7740

Please sign in to comment.