This repository has been archived by the owner on Jan 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Save schedule view via new useStoredState hook (#403)
* Create useStoredState hook * Use new stored state hook for calendar active view * Add clarifying remarks to hook documentation
- Loading branch information
1 parent
6104ddd
commit 6095334
Showing
2 changed files
with
32 additions
and
2 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,30 @@ | ||
import { useState } from 'react' | ||
|
||
/** | ||
* This functions like the useState hook, but it fetches the state stored in | ||
* local storage, via the given key, on subsequent uses. | ||
* | ||
* Do NOT call this twice with the same key - updating one of such a pair | ||
* will not update the other's state. | ||
* | ||
* Currently only works for strings, but can be generalized with JSON.parse | ||
* and JSON.stringify if needed. | ||
*/ | ||
export function useStoredState(initialState, key) { | ||
const storedState = localStorage.getItem(key) | ||
|
||
const [state, setState] = useState(() => { | ||
if (storedState === null) { | ||
localStorage.setItem(key, initialState) | ||
return initialState | ||
} | ||
return storedState | ||
}) | ||
|
||
function setAndStoreState(newState) { | ||
setState(newState) | ||
localStorage.setItem(key, newState) | ||
} | ||
|
||
return [state, setAndStoreState] | ||
} |
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