diff --git a/apps/viewer/layouts/TypebotPage.tsx b/apps/viewer/layouts/TypebotPage.tsx index f34464239..3e02ba7c5 100644 --- a/apps/viewer/layouts/TypebotPage.tsx +++ b/apps/viewer/layouts/TypebotPage.tsx @@ -32,6 +32,9 @@ export const TypebotPage = ({ isIE ? new Error('Internet explorer is not supported') : undefined ) const [resultId, setResultId] = useState() + const [variableUpdateQueue, setVariableUpdateQueue] = useState< + VariableWithValue[][] + >([]) useEffect(() => { setShowTypebot(true) @@ -71,13 +74,26 @@ export const TypebotPage = ({ } } + useEffect(() => { + if (!resultId || variableUpdateQueue.length === 0) return + Promise.all(variableUpdateQueue.map(sendNewVariables(resultId))).then() + setVariableUpdateQueue([]) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [resultId]) + const handleNewVariables = async (variables: VariableWithValue[]) => { - if (!resultId) return setError(new Error('Result was not created')) if (variables.length === 0) return - const { error } = await updateResult(resultId, { variables }) - if (error) setError(error) + if (!resultId) + return setVariableUpdateQueue([...variableUpdateQueue, variables]) + await sendNewVariables(resultId)(variables) } + const sendNewVariables = + (resultId: string) => async (variables: VariableWithValue[]) => { + const { error } = await updateResult(resultId, { variables }) + if (error) setError(error) + } + const handleNewAnswer = async (answer: Answer) => { if (!resultId) return setError(new Error('Result was not created')) const { error } = await upsertAnswer({ ...answer, resultId })