From 9e3796b568efb43aaa6d29782a607358e455517d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dafydd=20Ll=C5=B7r=20Pearson?= Date: Wed, 10 Jul 2024 10:28:46 +0100 Subject: [PATCH] fix: Indentify and fix bug - `currentCard()` is called multiple times which triggers the expensive `upcomingCardIds()` - Adding a static `currentCard` variable reduced calls (and thus multiple React re-renders) --- .../src/pages/FlowEditor/lib/store/preview.ts | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/editor.planx.uk/src/pages/FlowEditor/lib/store/preview.ts b/editor.planx.uk/src/pages/FlowEditor/lib/store/preview.ts index be77eeeb9b..7b107c0fd4 100644 --- a/editor.planx.uk/src/pages/FlowEditor/lib/store/preview.ts +++ b/editor.planx.uk/src/pages/FlowEditor/lib/store/preview.ts @@ -39,7 +39,8 @@ export interface PreviewStore extends Store.Store { upToNodeId: Store.nodeId, visited?: Array, ) => Array; - currentCard: () => Store.node | null; + currentCard: ({ id: Store.nodeId } & Store.node) | null; + setCurrentCard: () => void; hasPaid: () => boolean; previousCard: ( node: Store.node | null, @@ -136,18 +137,15 @@ export const previewStore: StateCreator< return res; }, - currentCard() { + setCurrentCard() { const { upcomingCardIds, flow } = get(); const upcoming = upcomingCardIds(); if (upcoming.length > 0) { const id = upcoming[0]; - return { - id, - ...flow[id], - }; + set({ currentCard: { id, ...flow[id] } }); } else { - return null; + set({ currentCard: null }); } }, @@ -287,6 +285,7 @@ export const previewStore: StateCreator< _nodesPendingEdit, changedNode, updateSectionData, + setCurrentCard, } = get(); if (!flow[id]) throw new Error(`id "${id}" not found`); @@ -370,6 +369,7 @@ export const previewStore: StateCreator< } } updateSectionData(); + setCurrentCard(); }, resultData(flagSet, overrides) { @@ -652,6 +652,8 @@ export const previewStore: StateCreator< return currentRequestedFiles || emptyFileList; }, + + currentCard: null, }); const knownNots = (