Answer the question
In order to leave comments, you need to log in
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
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;
});
};
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question