// @flow
export function useLocalStorage<T>(
  key: string,
  initialValue: T,
): [T, (T) => void] {
  let state;
  try {
    state = JSON.parse(window.localStorage.getItem(key));
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error('useLocalStorage: failed to load key', key, e);
  }

  const setter = (newValue: T) => {
    try {
      window.localStorage.setItem(key, JSON.stringify(newValue));
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error('useLocalStorage: failed to store value', newValue, e);
    }
  };

  return [state ?? initialValue, setter];
}
