A
A
Anastasia Tovma2021-09-18 12:39:35
React
Anastasia Tovma, 2021-09-18 12:39:35

How to store the state of whether the sidebar is open or closed using localstorage?

This is my first time using localstorage and I want to store state through hooks.
You need to remember whether the filter sidebar is shown or hidden. So far, everything in the code is clumsily simple, and when the page is updated, the data returns to its original position. Please guide in this matter.

const TaskRegionView = () => {
    const [condition, setCondition] = useState(true);

    const handleToggleCondition = () => {
        setCondition(prev => !prev);
    };
....
<Button onClick={handleToggleCondition} className={styles['button']}>
                    <LeftOutlined />
                </Button>
                {condition && (
                    <>
                        <Button onClick={handleToggleCondition} className={styles['button-open']}>
                            <RightOutlined />
                        </Button>
                        <Filter
                            className={styles['filter']}
                        />
                    </>
                )}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Ivanovich, 2021-09-18
@IwanQ

Didn't test but should coo

const TaskRegionView = () => {
    const isMenuOpenLocalStorageKey = '__isMenuOpen';
  
    const [condition, setCondition] = useState(() => {
      const value = localStorage.getItem(isMenuOpenLocalStorageKey);

     const isOpen = JSON.parse(value);
      
      if (isOpen === null) return false;
      
      return value;
    });

    const handleToggleCondition = () => {
        setCondition((prev) => {
          const state = !prev;
          
          localStorage.setItem(isMenuOpenLocalStorageKey, JSON.stringify(state));
          
          return state;
        });
    };
...

A
Alexander, 2021-09-18
@Seasle

usePersistedState

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question