Search code examples
reactjslocal-storagedropdownreact-select

Store dropdown selection and load it from localStorage


I want to store a couple of selection of some dropdowns where the number of these drop down is unknown because it's related to some API. So what I want is each time the page reloads it keeps the selection of each drop down remained as nothing changed


Solution

  • You can use localStorage.setItem() to update the selected options when onChange event fires and retrieve the data from the last session using localStorage.getItem() when the component is mounted again.

    Remember to serialize and deserialize the data when you set and get it. See this answer for more detail on why you should do that.

    import React from "react";
    import Select from "react-select";
    import options from "./options";
    
    const SELECT_VALUE_KEY = "MySelectValue";
    
    function MySelect() {
      const [selected, setSelected] = React.useState([]);
      const handleChange = (s) => {
        localStorage.setItem(SELECT_VALUE_KEY, JSON.stringify(s));
        setSelected(s);
      };
    
      React.useEffect(() => {
        const lastSelected = JSON.parse(
          localStorage.getItem(SELECT_VALUE_KEY) ?? "[]"
        );
        setSelected(lastSelected);
      }, []);
    
      return (
        <Select
          value={selected}
          onChange={handleChange}
          options={options}
          isMulti
        />
      );
    }
    

    Live Demo

    Edit 63994222/store-dropdown-selection-and-load-it-from-localssroage