diff --git a/src/App.jsx b/src/App.jsx index 85ffc61..8656f28 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,5 +1,63 @@ +import { useLocalStorage } from "./useLocalStorage" + function App() { - return "Hello World" + const [firstName, setFirstName] = useLocalStorage("FIRST_NAME", "") + + // Bonus: + const [lastName, setLastName] = useLocalStorage("LAST_NAME", () => { + return "Default" + }) + + // Bonus: + const [hobbies, setHobbies] = useLocalStorage("HOBBIES", [ + "Programming", + "Weight Lifting", + ]) + + return ( + <> +
+ + setFirstName(e.target.value)} + /> +
+ +
+ + setLastName(e.target.value)} + /> +
+ +
{hobbies.join(", ")}
+ + + ) } export default App diff --git a/src/useLocalStorage.js b/src/useLocalStorage.js new file mode 100644 index 0000000..4d36254 --- /dev/null +++ b/src/useLocalStorage.js @@ -0,0 +1,23 @@ +import { useEffect, useState } from "react" + +export function useLocalStorage(key, initialValue) { + let finalValue = localStorage.getItem(key) + if (finalValue == null) { + finalValue = + typeof initialValue === "function" ? initialValue() : initialValue + } else { + finalValue = JSON.parse(finalValue) + } + + const [value, setValue] = useState(finalValue) + + useEffect(() => { + if (value != null) { + localStorage.setItem(key, JSON.stringify(value)) + } else { + localStorage.removeItem(key) + } + }, [value, key]) + + return [value, setValue] +}