Total Complexity | 4 |
Complexity/F | 0 |
Lines of Code | 26 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import { useState } from 'react' |
||
2 | |||
3 | export const useSessionStorage = (key: string, initialValue: string) => { |
||
4 | const [storedValue, setStoredValue] = useState(() => { |
||
5 | try { |
||
6 | const item = window.sessionStorage.getItem(key) |
||
7 | return item ? JSON.parse(item) : initialValue |
||
8 | } catch (error) { |
||
9 | console.error(error) |
||
10 | return initialValue |
||
11 | } |
||
12 | }) |
||
13 | |||
14 | const setValue = (value: any) => { |
||
|
|||
15 | try { |
||
16 | const valueToStore = |
||
17 | value instanceof Function ? value(storedValue) : value |
||
18 | setStoredValue(valueToStore) |
||
19 | window.sessionStorage.setItem(key, JSON.stringify(valueToStore)) |
||
20 | } catch (error) { |
||
21 | console.log(error) |
||
22 | } |
||
23 | } |
||
24 | return [storedValue, setValue] |
||
25 | } |
||
26 |