From f422157016608eff8703e34f08493df46063dc19 Mon Sep 17 00:00:00 2001 From: Masen Furer Date: Thu, 12 Dec 2024 03:45:22 -0800 Subject: [PATCH] JSON5.parse in on_upload_progress handler responses --- reflex/.templates/web/utils/state.js | 47 ++++++++++++++++------------ 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/reflex/.templates/web/utils/state.js b/reflex/.templates/web/utils/state.js index 4be9a842f..304bc92de 100644 --- a/reflex/.templates/web/utils/state.js +++ b/reflex/.templates/web/utils/state.js @@ -445,8 +445,7 @@ export const connect = async ( }); // On each received message, queue the updates and events. - socket.current.on("event", async (message) => { - const update = message; + socket.current.on("event", async (update) => { for (const substate in update.delta) { dispatch[substate](update.delta[substate]); } @@ -458,7 +457,7 @@ export const connect = async ( }); socket.current.on("reload", async (event) => { event_processing = false; - queueEvents([...initialEvents(), JSON5.parse(event)], socket); + queueEvents([...initialEvents(), event], socket); }); document.addEventListener("visibilitychange", checkVisibility); @@ -499,23 +498,31 @@ export const uploadFiles = async ( // Whenever called, responseText will contain the entire response so far. const chunks = progressEvent.event.target.responseText.trim().split("\n"); // So only process _new_ chunks beyond resp_idx. - chunks.slice(resp_idx).map((chunk) => { - event_callbacks.map((f, ix) => { - f(chunk) - .then(() => { - if (ix === event_callbacks.length - 1) { - // Mark this chunk as processed. - resp_idx += 1; - } - }) - .catch((e) => { - if (progressEvent.progress === 1) { - // Chunk may be incomplete, so only report errors when full response is available. - console.log("Error parsing chunk", chunk, e); - } - return; - }); - }); + chunks.slice(resp_idx).map((chunk_json) => { + try { + const chunk = JSON5.parse(chunk_json); + event_callbacks.map((f, ix) => { + f(chunk) + .then(() => { + if (ix === event_callbacks.length - 1) { + // Mark this chunk as processed. + resp_idx += 1; + } + }) + .catch((e) => { + if (progressEvent.progress === 1) { + // Chunk may be incomplete, so only report errors when full response is available. + console.log("Error processing chunk", chunk, e); + } + return; + }); + }); + } catch (e) { + if (progressEvent.progress === 1) { + console.log("Error parsing chunk", chunk_json, e); + } + return; + } }); };