mirror of
https://github.com/emsesp/EMS-ESP32.git
synced 2025-12-07 00:09:51 +03:00
retain toggle in dashboard, refresh when new devices loaded
This commit is contained in:
26
interface/src/utils/usePersistState.ts
Normal file
26
interface/src/utils/usePersistState.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
export const usePersistState = <T>(
|
||||
initial_value: T,
|
||||
id: string
|
||||
): [T, (new_state: T) => void] => {
|
||||
// Set initial value
|
||||
const _initial_value = useMemo(() => {
|
||||
const local_storage_value_str = localStorage.getItem('state:' + id);
|
||||
// If there is a value stored in localStorage, use that
|
||||
if (local_storage_value_str) {
|
||||
return JSON.parse(local_storage_value_str);
|
||||
}
|
||||
// Otherwise use initial_value that was passed to the function
|
||||
return initial_value;
|
||||
}, []);
|
||||
|
||||
const [state, setState] = useState(_initial_value);
|
||||
|
||||
useEffect(() => {
|
||||
const state_str = JSON.stringify(state); // Stringified state
|
||||
localStorage.setItem('state:' + id, state_str); // Set stringified state as item in localStorage
|
||||
}, [state]);
|
||||
|
||||
return [state, setState];
|
||||
};
|
||||
Reference in New Issue
Block a user