|
| 1 | +import { useContext, useEffect, useState } from "react"; |
| 2 | +import { SnapshotContext } from "../../providers/snapshot-provider"; |
| 3 | + |
| 4 | +export default function useSnapShotState<T>( |
| 5 | + key: string, |
| 6 | + initialValue?: T, |
| 7 | + onRestore?: (value: T) => void |
| 8 | +) { |
| 9 | + const snapshotContext = useContext(SnapshotContext); |
| 10 | + |
| 11 | + if (!snapshotContext) { |
| 12 | + throw new Error("useSnapShotState must be used within a SnapshotProvider"); |
| 13 | + } |
| 14 | + |
| 15 | + const { states, setStates } = snapshotContext; |
| 16 | + |
| 17 | + // Initialize state with the value from context or the initial value |
| 18 | + const [state, setState] = useState<T>( |
| 19 | + states[key] !== undefined ? states[key] : initialValue |
| 20 | + ); |
| 21 | + |
| 22 | + // Update context whenever state changes |
| 23 | + const setSnapshotState: React.Dispatch<React.SetStateAction<T>> = (value) => { |
| 24 | + setState((prev) => { |
| 25 | + const newValue = |
| 26 | + typeof value === "function" ? (value as (prev: T) => T)(prev) : value; |
| 27 | + |
| 28 | + // Defer the setStates call to next microtask, outside render phase |
| 29 | + Promise.resolve().then(() => { |
| 30 | + setStates((prevStates) => ({ |
| 31 | + ...prevStates, |
| 32 | + [key]: newValue, |
| 33 | + })); |
| 34 | + }); |
| 35 | + |
| 36 | + return newValue; |
| 37 | + }); |
| 38 | + }; |
| 39 | + |
| 40 | + // Set the initial value in context if not already set |
| 41 | + useEffect(() => { |
| 42 | + // Only set if the key does not exist in the context |
| 43 | + if (states[key] === undefined && initialValue !== undefined) { |
| 44 | + setStates((prevStates) => ({ |
| 45 | + ...prevStates, |
| 46 | + [key]: initialValue, |
| 47 | + })); |
| 48 | + } |
| 49 | + }, []); |
| 50 | + |
| 51 | + // Restore state from context when key or states change |
| 52 | + useEffect(() => { |
| 53 | + console.log("Restoring state for key:", key, states[key]); |
| 54 | + |
| 55 | + if (states[key] !== undefined && states[key] !== state) { |
| 56 | + setState(states[key]); |
| 57 | + if (onRestore) { |
| 58 | + onRestore(states[key]); |
| 59 | + } |
| 60 | + } |
| 61 | + }, [states[key]]); |
| 62 | + |
| 63 | + return [state, setSnapshotState] as const; |
| 64 | +} |
0 commit comments