Skip to content

Commit cc6c82b

Browse files
committed
set up singleton pattern for esbuild initialization to resolve multiple click issue on CODE PREVIEW button
1 parent 3fe99a4 commit cc6c82b

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

app/src/components/bottom/CodePreview.tsx

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import 'ace-builds/src-noconflict/mode-javascript';
44
import 'ace-builds/src-noconflict/theme-dracula';
55
import 'ace-builds/src-noconflict/theme-terminal';
66

7-
import * as esbuild from 'esbuild-wasm';
8-
97
import React, { useContext, useEffect, useRef, useState } from 'react';
108
import {
119
codePreviewInput,
@@ -19,22 +17,14 @@ import { RootState } from '../../redux/store';
1917
import { fetchPlugin } from '../../plugins/fetch-plugin';
2018
import { unpkgPathPlugin } from '../../plugins/unpkg-path-plugin';
2119
import useResizeObserver from '../../tree/useResizeObserver';
20+
import { initializeEsbuild } from '../../helperFunctions/esbuildService';
2221

2322
const CodePreview: React.FC<{
2423
theme: string | null;
2524
setTheme: any | null;
2625
}> = ({ theme, setTheme }) => {
2726
const ref = useRef<any>();
2827

29-
/**
30-
* Starts the Web Assembly service.
31-
*/
32-
const startService = async () => {
33-
ref.current = await esbuild.initialize({
34-
worker: true,
35-
wasmURL: 'https://unpkg.com/[email protected]/esbuild.wasm'
36-
});
37-
};
3828
const dispatch = useDispatch();
3929

4030
const wrapper = useRef();
@@ -49,7 +39,8 @@ const CodePreview: React.FC<{
4939
const [input, setInput] = useState('');
5040

5141
useEffect(() => {
52-
startService();
42+
//Starts the Web Assembly service
43+
initializeEsbuild();
5344
}, []);
5445

5546
useEffect(() => {
@@ -61,6 +52,13 @@ const CodePreview: React.FC<{
6152
dispatch(codePreviewInput(currentComponent.code));
6253
}, [currentComponent, state.components]);
6354

55+
useEffect(() => {
56+
console.log('CodePreview Mounted');
57+
return () => {
58+
console.log('CodePreview Unmounted');
59+
};
60+
}, []);
61+
6462
/**
6563
* Handler thats listens to changes in code editor
6664
* @param {string} data - Code entered by the user
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import * as esbuild from 'esbuild-wasm';
2+
3+
/* Singleton pattern for initializing esbuild */
4+
/* This ensures that esbuild is only initialized once, regardless of how many times CodePreview is mounted and unmounted */
5+
let isEsbuildInitialized = false;
6+
7+
export const initializeEsbuild = async () => {
8+
if (!isEsbuildInitialized) {
9+
await esbuild.initialize({
10+
worker: true,
11+
wasmURL: 'https://unpkg.com/[email protected]/esbuild.wasm'
12+
});
13+
isEsbuildInitialized = true;
14+
}
15+
};

0 commit comments

Comments
 (0)