All files / src/hooks useStorage.js

100% Statements 18/18
100% Branches 5/5
100% Functions 5/5
100% Lines 17/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        9x 6x   6x   5x     1x 1x         9x   9x 4x 4x         9x 2x   2x   2x   1x     1x       9x    
import { useState, useEffect } from "react"
 
// https://usehooks.com/useLocalStorage/
export function useStorage(key, initialValue, storage = window.localStorage) {
    const getValue = (key, initialValue) => {
        try {
            // Get from local storage by key
            const item = storage.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
        }
    }
    // State to store our value
    // Pass initial state function to useState so logic is only executed once
    const [storedValue, setStoredValue] = useState(() => getValue(key, initialValue))
 
    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 to local storage
            storage.setItem(key, JSON.stringify(valueToStore))
            // Save state
            setStoredValue(valueToStore)
        } catch (error) {
            // A more advanced implementation would handle the error case
            console.log(error)
        }
    }
 
    return [storedValue, setValue]
}