import { useState, useEffect } from 'react';

function getStorageValue (key: string, defaultValue: any) {
    if (typeof window !== 'undefined') {
        const saved = localStorage.getItem(key);
        return saved || defaultValue;
    }
};

export function deleteStorageKey (key: string) {
    if (typeof window !== 'undefined') {
        localStorage.removeItem(key);
    }
};

export const useLocalStorage = (key: string, defaultValue: any) => {
    const [value, setValue] = useState(() => {
        return getStorageValue(key, defaultValue);
    });

    useEffect(() => {
        localStorage.setItem(key, value);
    }, [key, value]);

    return [value, setValue];
};
