-
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.
Merge pull request #48 from erland-syafiq/persistant-registration-form
Persistant registration form
- Loading branch information
Showing
3 changed files
with
53 additions
and
17 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 |
---|---|---|
@@ -0,0 +1,32 @@ | ||
"use client"; | ||
|
||
import { useEffect, useState } from "react"; | ||
|
||
/** | ||
* Hook to automatically save state to local storage. | ||
* | ||
* @param {string} key - unique key for storage | ||
* @param {any | Function} initialValue - initial value can be function | ||
* @returns {[any, Function]} the same values as setState | ||
*/ | ||
export default function useLocalStorage(key, initialValue) { | ||
const [state, setState] = useState(initialValue); | ||
|
||
function setStoredState(newState) { | ||
localStorage.setItem(key, JSON.stringify(newState)); | ||
setState(newState); | ||
} | ||
|
||
useEffect(() => { | ||
const savedValue = localStorage.getItem(key); | ||
|
||
if (savedValue) { | ||
setState(JSON.parse(savedValue)) | ||
} | ||
else { | ||
localStorage.setItem(key, JSON.stringify(newState)); | ||
} | ||
}, []) | ||
|
||
return [state, setStoredState]; | ||
} |
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