From be147d218b9d3a21dbbb81d6cbe0853cab37eead Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Mon, 27 May 2024 06:59:26 -0600 Subject: [PATCH] Fix optimistic state (#11556) --- web/src/hooks/use-optimistic-state.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/web/src/hooks/use-optimistic-state.ts b/web/src/hooks/use-optimistic-state.ts index ca33fe885..0b47dd4ff 100644 --- a/web/src/hooks/use-optimistic-state.ts +++ b/web/src/hooks/use-optimistic-state.ts @@ -3,11 +3,11 @@ import { useState, useEffect, useCallback, useRef } from "react"; type OptimisticStateResult = [T, (newValue: T) => void]; const useOptimisticState = ( - initialState: T, + currentState: T, setState: (newValue: T) => void, delay: number = 20, ): OptimisticStateResult => { - const [optimisticValue, setOptimisticValue] = useState(initialState); + const [optimisticValue, setOptimisticValue] = useState(currentState); const debounceTimeout = useRef | null>(null); const handleValueChange = useCallback( @@ -37,6 +37,16 @@ const useOptimisticState = ( }; }, []); + 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]; };