All files / src/hooks useLocalStorage.js

83.33% Statements 15/18
75% Branches 3/4
100% Functions 5/5
82.35% Lines 14/17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47    1x 3x   3x   3x                       5x   5x 2x 2x         5x 1x   1x   1x   1x             5x        
import React from "react"
 
const getValue = (key, initialValue) => {
    try {
        // Get from local storage by key
        const item = window.localStorage.getItem(key)
        // Parse stored json or if none return initialValue
        return item ? JSON.parse(item) : initialValue
    } catch (error) {
        // If error also return initialValue
        console.log(error)
        return initialValue
    }
}
 
// https://usehooks.com/useLocalStorage/
function useLocalStorage(key, initialValue) {
    // State to store our value
    // Pass initial state function to useState so logic is only executed once
    const [storedValue, setStoredValue] = React.useState(() => getValue(key, initialValue))
 
    React.useEffect(() => {
        const val = getValue(key, initialValue)
        setStoredValue(val)
    }, [key])
 
    // Return a wrapped version of useState's setter function that ...
    // ... persists the new value to localStorage.
    const setValue = value => {
        try {
            // Allow value to be a function so we have same API as useState
            const valueToStore = value instanceof Function ? value(storedValue) : value
            // Save state
            setStoredValue(valueToStore)
            // Save to local storage
            window.localStorage.setItem(key, JSON.stringify(valueToStore))
        } catch (error) {
            // A more advanced implementation would handle the error case
            console.log(error)
        }
    }
 
    return [storedValue, setValue]
}
 
export default useLocalStorage