import { useState, useEffect } from 'react';

const useLocalStorage = (key: string, type: 'local' | 'session' = 'local') => {
  const [state, setState] = useState(() => {
    try {
      const localStorageValue =
        type === 'local' ? localStorage.getItem(key) : sessionStorage.getItem(key);
      return JSON.parse(localStorageValue || 'null');
    } catch (error) {
      console.error(error);
    }
  });

  useEffect(() => {
    try {
      const serializedState = JSON.stringify(state);
      type === 'local'
        ? localStorage.setItem(key, serializedState)
        : sessionStorage.setItem(key, serializedState);
    } catch (error) {
      console.error(error);
    }
  }, [state]);

  return [state, setState];
};

export default useLocalStorage;
