"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useLocalStorage = void 0;
var _react = require("react");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

/**
 * A hook that works like `useState`, but persisted to localStorage.
 *
 * example:
 *
 * const [foo, setFoo] = useLocalStorage("foo", "bar");
 *
 * console.log(foo) // "bar"
 * setFoo("baz")
 * console.log(foo) // "baz"
 *
 * // Navigate away from page and return
 *
 * const [foo, setFoo] = useLocalStorage("foo", "bar");
 * console.log(foo) // "baz"
 */
const useLocalStorage = (key, defaultValue) => {
  const saveToStorage = value => window.localStorage.setItem(key, JSON.stringify(value));
  const removeFromStorage = () => window.localStorage.removeItem(key);
  const getFromStorage = () => {
    const storedItem = window.localStorage.getItem(key);
    if (!storedItem) return;
    let parsedItem;
    try {
      return JSON.parse(storedItem);
    } catch (e) {
      removeFromStorage();
    }
    return parsedItem;
  };
  const storedItem = getFromStorage();
  if (!storedItem) {
    saveToStorage(defaultValue);
  }
  const toStore = storedItem || defaultValue;
  const [item, setItem] = (0, _react.useState)(toStore);
  const saveItem = value => {
    saveToStorage(value);
    setItem(value);
  };
  return [item, saveItem];
};
exports.useLocalStorage = useLocalStorage;