diff --git a/README.md b/README.md index 90112e5..c94dffb 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,14 @@ Any changes to state in one tab will be rendered on the other tab. You can also close the browser and the next time you run your app, the state will be rendered as it was before you closed your browser. +Besides localStorage, we also provide built-in support for `sessionStorage`, +just import `useSessionStorage` and pass its call as the second parameter. + +```js +import createPersistedState, { useSessionStorage } from 'use-persisted-state'; +const useCounterState = createPersistedState('count', useSessionStorage()); +``` + ## License **[MIT](LICENSE)** Licensed diff --git a/package.json b/package.json index 576c0cf..86e8d5f 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,8 @@ "utils", "lib", "persistent", - "localstorage" + "localstorage", + "sessionstorage" ], "author": "donavon", "devDependencies": { diff --git a/src/index.js b/src/index.js index 75b2df6..a05ab65 100644 --- a/src/index.js +++ b/src/index.js @@ -21,6 +21,24 @@ const getProvider = () => { return null; }; +const useSessionStorage = () => { + if (typeof global !== 'undefined' && global.sessionStorage) { + return global.sessionStorage; + } + // eslint-disable-next-line no-undef + if (typeof globalThis !== 'undefined' && globalThis.sessionStorage) { + // eslint-disable-next-line no-undef + return globalThis.sessionStorage; + } + if (typeof window !== 'undefined' && window.sessionStorage) { + return window.sessionStorage; + } + if (typeof sessionStorage !== 'undefined') { + return sessionStorage; + } + return null; +} + const createPersistedState = (key, provider = getProvider()) => { if (provider) { const storage = createStorage(provider); @@ -30,3 +48,5 @@ const createPersistedState = (key, provider = getProvider()) => { }; export default createPersistedState; + +export { useSessionStorage }