I'm currently working on creating a Singleton instance for a dynamically imported module in my Next.js app. However, the problem is that each time I call getInstance
, it initializes a new instance instead of reusing the existing one.
The following code snippet in gui.js
displays the implementation:
let loadDynamicModule = async () => {
let GUI;
await import('three/examples/jsm/libs/dat.gui.module.js')
.then(module => {
GUI = module.GUI
})
.catch(e => console.log(e))
return GUI;
}
let GUI = (function () {
let instance;
return {
getInstance: async () => {
if (!instance) {
let GUIModule = await loadDynamicModule();
instance = new GUIModule();
}
return instance;
}
};
})();
export default GUI;
To utilize this function within an ES6 class method, you can use
GUI.getInstance().then(g => { ... })
In typical scenarios, React Context API or Redux would be used for managing shared state. However, in this specific case, the requirement is to stick with pure ES6 JavaScript without relying on React.