Skip to content

Commit

Permalink
Fix optimistic state (#11556)
Browse files Browse the repository at this point in the history
  • Loading branch information
NickM-27 committed May 27, 2024
1 parent 7a9ee63 commit be147d2
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions web/src/hooks/use-optimistic-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { useState, useEffect, useCallback, useRef } from "react";
type OptimisticStateResult<T> = [T, (newValue: T) => void];

const useOptimisticState = <T>(
initialState: T,
currentState: T,
setState: (newValue: T) => void,
delay: number = 20,
): OptimisticStateResult<T> => {
const [optimisticValue, setOptimisticValue] = useState<T>(initialState);
const [optimisticValue, setOptimisticValue] = useState<T>(currentState);
const debounceTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);

const handleValueChange = useCallback(
Expand Down Expand Up @@ -37,6 +37,16 @@ const useOptimisticState = <T>(
};
}, []);

useEffect(() => {
if (currentState != optimisticValue) {
setOptimisticValue(currentState);
}
// sometimes an external action will cause the currentState to change
// without handleValueChange being called. In this case
// we need to update the optimistic value so the UI reflects the change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentState]);

return [optimisticValue, handleValueChange];
};

Expand Down

0 comments on commit be147d2

Please sign in to comment.