From a1b2f0344a59e24ae4d16f1689a02ba72ced2b53 Mon Sep 17 00:00:00 2001 From: Kero van Gelder Date: Wed, 5 Apr 2023 14:33:00 +0200 Subject: =?UTF-8?q?=F0=9F=90=9B=20Avoid=20a=20race=20condition=20when=20di?= =?UTF-8?q?spatch=20is=20used=20twice=20from=20outside=20(#8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Upgrade examples to lustre 2.0 * Upgrade to gleam 0.27.0 * Fix: avoid a race condition when dispatch is used twice from outside E.g. websocket open + websocket msg arriving Application returns a Cmd from update(model, msg) but the Effect handler is *not* ran be React 18 before the websocket msg-arriving is handled by the Reducer. Result: The Cmd returned by update(model, msg) is dropped silently. --------- Co-authored-by: Kero van Gelder --- src/ffi.mjs | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/ffi.mjs b/src/ffi.mjs index cb458d4..b6883d4 100644 --- a/src/ffi.mjs +++ b/src/ffi.mjs @@ -35,20 +35,37 @@ export const mount = ({ init, update, render }, selector) => { // let dispatch = null; + let init_cmds = null; + const App = React.createElement(() => { - const [[state, cmds], $dispatch] = React.useReducer( - ([state, _], action) => update(state, action), - init + const [state, $dispatch] = React.useReducer( + (state, action) => { + let [new_state, cmds] = update(state, action) + // Handle cmds immediately, they're not React-kind-of-state + for (const cmd of Cmd.to_list(cmds)) { + cmd(dispatch); + } + return new_state + }, + undefined, + () => { + let [state, cmds] = init + // postpone handling cmds, as we do not have the dispatch, yet + init_cmds = cmds + return state + } ); - const el = render(state); if (dispatch === null) dispatch = $dispatch; + const el = render(state); + React.useEffect(() => { - for (const cmd of Cmd.to_list(cmds)) { + for (const cmd of Cmd.to_list(init_cmds)) { cmd($dispatch); } - }, [cmds]); + init_cmds = undefined; // Just so we get an error, rather than re-execute + }, []); // empty deps array means this effect will only run on initial render return typeof el == "string" ? el : el($dispatch); }); -- cgit v1.2.3