1- import { useState } from "react" ;
1+ import { useState } from 'react' ;
2+
3+ /**
4+ * A function which fetches the value corresponding to the key from localStorage.
5+ * If the item doesn't exist returns the input value.
6+ *
7+ * @param {* } value
8+ * @param {string } key Key for the localStorage.
9+ * @returns {* } The value fetched from localStorage.
10+ */
11+ const getItem = ( value , key ) => {
12+ try {
13+ const item = localStorage . getItem ( key ) ;
14+ return item ? JSON . parse ( item ) : value ;
15+ } catch ( error ) {
16+ // If something went wrong returns the value itself.
17+ return value ;
18+ }
19+ } ;
220
321/**
422 * Custom useState hook which saves the state value in localStorage
@@ -8,41 +26,22 @@ import { useState } from "react";
826 * @returns {Array } Array containing stateful value and updater function.
927 */
1028const useLocalStorage = ( initialValue , key ) => {
11- const [ storedValue , setStoredValue ] = useState ( _getItem ( initialValue , key ) ) ;
29+ const [ storedValue , setStoredValue ] = useState ( getItem ( initialValue , key ) ) ;
1230
1331 const setValue = ( value ) => {
14- if ( typeof localStorage !== " undefined" ) {
15- //If value passed is a function, evaluating the function.
32+ if ( typeof localStorage !== ' undefined' ) {
33+ // If value passed is a function, evaluating the function.
1634 const valueToStore = value instanceof Function ? value ( storedValue ) : value ;
1735
18- //Setting state and saving the value to localStorage.
36+ // Setting state and saving the value to localStorage.
1937 setStoredValue ( valueToStore ) ;
2038 localStorage . setItem ( key , JSON . stringify ( valueToStore ) ) ;
2139 } else {
22- console . error ( " localStorage does not exist" ) ;
40+ throw new Error ( ' localStorage does not exist' ) ;
2341 }
2442 } ;
2543
2644 return [ storedValue , setValue ] ;
2745} ;
2846
29- /**
30- * A function which fetches the value corresponding to the key from localStorage.
31- * If the item doesn't exist returns the input value.
32- *
33- * @param {* } value
34- * @param {string } key Key for the localStorage.
35- * @returns {* } The value fetched from localStorage.
36- */
37- const _getItem = ( value , key ) => {
38- try {
39- const item = localStorage . getItem ( key ) ;
40- return item ? JSON . parse ( item ) : value ;
41- } catch ( error ) {
42- //If something went wrong returns the value itself.
43- console . error ( error ) ;
44- return value ;
45- }
46- } ;
47-
4847export default useLocalStorage ;
0 commit comments