From e05445a8d6e7746b4123a436b9e57864eabf5436 Mon Sep 17 00:00:00 2001 From: James Singleton Date: Sat, 23 Nov 2019 12:22:37 -0700 Subject: [PATCH] feat(hook): add useSessionStorage hook --- README.md | 2 +- src/hooks/useSessionStorage.jsx | 29 +++++++++++++++++++++++++++++ src/index.js | 1 + 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 src/hooks/useSessionStorage.jsx diff --git a/README.md b/README.md index b5b2da6b..af8e23f7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

Welcome to Hooks Arsenal 👋

+

Welcome to Hooks Arsenal 🎣

CircleCI diff --git a/src/hooks/useSessionStorage.jsx b/src/hooks/useSessionStorage.jsx new file mode 100644 index 00000000..7cfe5024 --- /dev/null +++ b/src/hooks/useSessionStorage.jsx @@ -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; diff --git a/src/index.js b/src/index.js index 3b895496..60b213ec 100644 --- a/src/index.js +++ b/src/index.js @@ -1,2 +1,3 @@ /* eslint-disable import/prefer-default-export */ export { default as useLocalStorage } from './hooks/useLocalStorage'; +export { default as useSessionStorage } from './hooks/useSessionStorage';