Skip to content

Commit

Permalink
feat(hook): add useSessionStorage hook
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesSingleton committed Nov 23, 2019
1 parent 7806528 commit e05445a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<h1 align="center">Welcome to Hooks Arsenal 👋</h1>
<h1 align="center">Welcome to Hooks Arsenal 🎣</h1>
<p>
<img alt="CircleCI" src="https://img.shields.io/circleci/build/github/JamesSingleton/hooks-arsenal">
<a href="https://www.npmjs.com/package/hooks-arsenal">
Expand Down
29 changes: 29 additions & 0 deletions src/hooks/useSessionStorage.jsx
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;
1 change: 1 addition & 0 deletions src/index.js
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';

0 comments on commit e05445a

Please sign in to comment.