I have a class in my react app which uses 'Builder Pattern' and I've imported it in some nested components in my page. for example in parent component and child component, too.
But it seems it calls the class's constructor once! and in second instantiate it has existing data which I've added in previews in previews instantiate. (Not a new and clean instantiate!)
// [Builder pattern]
class Requester {
constructor() {
this.definedHeaders = {}
console.log('construct', this)
}
contentType(contenttype) {
this.definedHeaders['Content-Type'] = contenttype
return this;
}
async get(url) {
// ...
}
async post(url, data = {}, isFormData = false) {
// ...
}
}
export default new Requester();
ES modules are evaluated only once, when they are imported the first time. This trait is common to all JavaScript module implementations.
Because of that, exporting class instance is a common way to make class a singleton. That a class itself isn't exported prevents from creating additional instances.
If the intention is to not have a single instance, a class itself should be exported:
export default class Requester {...}
And instantiated in places where it's used:
import Requester from '...';
const requester = new Requester;