-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(hook): add useSessionStorage hook
- Loading branch information
1 parent
7806528
commit e05445a
Showing
3 changed files
with
31 additions
and
1 deletion.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { useEffect, useState } from 'react'; | ||
|
||
const useSessionStorage = (key, initialValue, raw) => { | ||
const [sessionStoredValue, setSessionStoredValue] = useState(() => { | ||
try { | ||
const sessionStorageValue = sessionStorage.getItem(key); | ||
if (typeof sessionStorageValue !== 'string') { | ||
sessionStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue)); | ||
return initialValue; | ||
} | ||
|
||
return raw ? sessionStorageValue : JSON.parse(sessionStorageValue || 'null'); | ||
} catch (error) { | ||
return initialValue; | ||
} | ||
}); | ||
|
||
useEffect(() => { | ||
try { | ||
const serializedState = raw ? String(sessionStoredValue) : JSON.stringify(sessionStoredValue); | ||
sessionStorage.setItem(key, serializedState); | ||
} catch (error) { | ||
console.error(error); | ||
} | ||
}); | ||
return [sessionStoredValue, setSessionStoredValue]; | ||
}; | ||
|
||
export default useSessionStorage; |
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,2 +1,3 @@ | ||
/* eslint-disable import/prefer-default-export */ | ||
export { default as useLocalStorage } from './hooks/useLocalStorage'; | ||
export { default as useSessionStorage } from './hooks/useSessionStorage'; |