Skip to content

Commit

Permalink
Fix fast refresh for previews after #726 (#805)
Browse files Browse the repository at this point in the history
This PR fixes fast refresh of previews after a regression introduced in
#726

The issue that started occuring in #726 was that previews after getting
fast refresh would sometimes fail to render. Here's an example of
problematic component:
https://github.com/software-mansion-labs/radon-ide-demo/blob/main/src/components/Message.tsx#L21
– when you update emoji list in that component, the render would throw
exception when attempting to access styles.

The reason for the above exception was that in #726 we started
triggering state updates. However, the state update would be triggered
at the point when preview method is called which is before the whole
file is executed. As a consequence, we'd still try to render the old
version of component that would trigger for hoisted variables – in this
instance it'd be because of styles that are defined after component is
defined.

The fix is to allow the fast refresh to finish processing updates. The
only thing that's necessary is to trigger state update in the next cycle
of JS loop. In this PR we're adding `setTimeout(fun, 0)` to allow for
the state update to run in the following loop cycle as opposed to
immediately when preview method is called.

Note that it is safe not to read lastPreview in the method that is move
to timeout. This is ok, because the last preview may only update as a
result of the Preview container being rendered. So if the Preview
component gets rendered, there's no reason for us to also trigger that
re-render.

### How Has This Been Tested: 
1. Open
https://github.com/software-mansion-labs/radon-ide-demo/blob/main/src/components/Message.tsx#L21
and modify list of emojis – before it'd throw exception upon saving, now
the preview updates properly
2. Test the scenario from #726 to make sure the updates attributes are
still processed properly after this change: one way is to add prop to
emoji container and update it to see the changes getting reflected in
the preview.
  • Loading branch information
kmagiera authored Dec 1, 2024
1 parent 2adfe74 commit 990e515
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion packages/vscode-extension/lib/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export function preview(component) {

// send update request to the last preview instance if it existed
if (lastPreview && lastPreview.renderTrigger) {
lastPreview.renderTrigger();
setTimeout(lastPreview.renderTrigger, 0);
}
}

Expand Down

0 comments on commit 990e515

Please sign in to comment.