Skip to content

Commit

Permalink
refactor(graph): Enhance state management in GraphProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
toyamarinyon committed Oct 25, 2024
1 parent 01290fa commit 3dcee6f
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions app/(playground)/p/[agentId]/beta-proto/graph/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,33 +31,37 @@ export const GraphProvider: FC<PropsWithChildren<GraphProviderProps>> = ({
agentId,
defaultGraph,
}) => {
const [state, originalDispatch] = useReducer(graphReducer, {
const [originalState, originalDispatch] = useReducer(graphReducer, {
graph: defaultGraph,
});
const isInitialMount = useRef(true);
const stateRef = useRef(originalState);

useEffect(() => {
stateRef.current = originalState;
}, [originalState]);

const deboucedSetGraphToDb = useDebounce(async (graph: Graph) => {
setGraphToDb(agentId, graph);
}, 500);
const enhancedDispatch: EnhancedDispatch = useCallback(
async (action) => {
if (typeof action === "function") {
await action(enhancedDispatch, () => state);
} else {
originalDispatch(action);
}
},
[state],
);
const enhancedDispatch: EnhancedDispatch = useCallback(async (action) => {
if (typeof action === "function") {
await action(enhancedDispatch, () => stateRef.current);
} else {
originalDispatch(action);
}
}, []);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
} else {
deboucedSetGraphToDb(state.graph);
deboucedSetGraphToDb(originalState.graph);
}
}, [state, deboucedSetGraphToDb]);
}, [originalState, deboucedSetGraphToDb]);
return (
<GraphContext.Provider value={{ state, dispatch: enhancedDispatch }}>
<GraphContext.Provider
value={{ state: originalState, dispatch: enhancedDispatch }}
>
{children}
</GraphContext.Provider>
);
Expand Down

0 comments on commit 3dcee6f

Please sign in to comment.