Skip to content

Commit

Permalink
Merge pull request #65 from toyamarinyon/improve-debounce
Browse files Browse the repository at this point in the history
refactor(graph): Inline debounce logic in GraphProvider
  • Loading branch information
toyamarinyon authored Oct 30, 2024
2 parents 44ac7a7 + 3b5ca3d commit 9813f8e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 48 deletions.
42 changes: 24 additions & 18 deletions app/(playground)/p/[agentId]/beta-proto/graph/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { type EnhancedDispatch, GraphContext } from "./context";
import { graphReducer } from "./reducer";
import { setGraphToDb } from "./server-actions";
import type { Graph } from "./types";
import { useDebounce } from "./use-debounce";

const initialState = {
graph: {
Expand All @@ -34,25 +33,32 @@ export const GraphProvider: FC<PropsWithChildren<GraphProviderProps>> = ({
const isInitialMount = useRef(true);
const stateRef = useRef({ graph: defaultGraph });
const [state, setState] = useState(stateRef.current);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);

const deboucedSetGraphToDb = useDebounce(async (graph: Graph) => {
setGraphToDb(agentId, graph);
}, 500);
const enhancedDispatch: EnhancedDispatch = useCallback(async (action) => {
if (typeof action === "function") {
await action(enhancedDispatch, () => stateRef.current);
} else {
stateRef.current = graphReducer(stateRef.current, action);
}
setState(stateRef.current);
}, []);
const enhancedDispatch: EnhancedDispatch = useCallback(
async (action) => {
if (typeof action === "function") {
await action(enhancedDispatch, () => stateRef.current);
} else {
stateRef.current = graphReducer(stateRef.current, action);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(async () => {
await setGraphToDb(agentId, stateRef.current.graph);
}, 500);
}
setState(stateRef.current);
},
[agentId],
);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
} else {
deboucedSetGraphToDb(stateRef.current.graph);
}
}, [deboucedSetGraphToDb]);
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return (
<GraphContext.Provider value={{ state, dispatch: enhancedDispatch }}>
{children}
Expand Down
30 changes: 0 additions & 30 deletions app/(playground)/p/[agentId]/beta-proto/graph/use-debounce.ts

This file was deleted.

0 comments on commit 9813f8e

Please sign in to comment.