Istvan Orban
Istvan Orban

Reputation: 1685

How to create singleton class when I importing it from multiple places?

How can I make a Singleton class if I want to import it at multiple places?

I ended up with something like this, but I am exporting a new() instance (at least I think so) at each time I import it.

class RenderToRootAPI {
    renderToRootComponent = null
    setRenderComponent = ref => this.renderToRootComponent = ref
    setInstance = instance =>  {
        console.warn('setting instance')
        this.renderToRootComponent.setInstance(instance)
    }
    deleteInstance = () => this.renderToRootComponent.deleteInstance
}

export default new RenderToRootAPI()

Upvotes: 2

Views: 1372

Answers (1)

Tholle
Tholle

Reputation: 112897

What you have written will export a singleton. It doesn't matter how many times you import it.

It might look a bit more clear if you write it like this as an example:

class RenderToRootAPI {
    renderToRootComponent = null
    setRenderComponent = ref => this.renderToRootComponent = ref
    setInstance = instance =>  {
        console.warn('setting instance')
        this.renderToRootComponent.setInstance(instance)
    }
    deleteInstance = () => this.renderToRootComponent.deleteInstance
}

const renderToRootAPI = new RenderToRootAPI();

export default renderToRootAPI;

The class is not even exported, and the single exported instance will be used in all the modules that import it.

Upvotes: 4

Related Questions