-
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.
feat: implement local storage for task management and enhance TaskCar…
…d styling
- Loading branch information
1 parent
94b60ed
commit 6012160
Showing
3 changed files
with
56 additions
and
9 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
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
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,10 +1,57 @@ | ||
import { useContext } from "react"; | ||
import { | ||
Dispatch, | ||
SetStateAction, | ||
useContext, | ||
useEffect, | ||
useRef, | ||
useState, | ||
} from "react"; | ||
import { TaskContext } from "../contexts/task-context"; | ||
|
||
export const useTaskContext = () => { | ||
export function useTaskContext() { | ||
const context = useContext(TaskContext); | ||
if (!context) { | ||
throw new Error("useTaskContext must be used within a TaskProvider"); | ||
} | ||
return context; | ||
}; | ||
} | ||
|
||
type InitialValueType<T> = T | (() => T); | ||
|
||
export function useLocalStorage<T>( | ||
key: string, | ||
initialValue: InitialValueType<T>, | ||
{ serialize = JSON.stringify, deserialize = JSON.parse } = {} | ||
): [T, Dispatch<SetStateAction<T>>] { | ||
const [storedValue, setStoredValue] = useState<T>(() => { | ||
try { | ||
const item = window.localStorage.getItem(key); | ||
if (item) { | ||
return deserialize(item); | ||
} | ||
|
||
return initialValue instanceof Function ? initialValue() : initialValue; | ||
} catch (error) { | ||
console.error(error); | ||
return initialValue; | ||
} | ||
}); | ||
|
||
const prevKeyRef = useRef(key); | ||
|
||
// Use useEffect to update localstorage when value changes | ||
useEffect(() => { | ||
try { | ||
if (prevKeyRef.current !== key) { | ||
window.localStorage.removeItem(prevKeyRef.current); | ||
} | ||
|
||
prevKeyRef.current = key; | ||
window.localStorage.setItem(key, serialize(storedValue)); | ||
} catch (error) { | ||
console.error(error); | ||
} | ||
}, [storedValue, serialize, key]); | ||
|
||
return [storedValue, setStoredValue]; | ||
} |