Reputation: 4437
I have a comment app in react:
require('console-polyfill')
import 'babel-polyfill'
import React from 'react'
import ReactDOM from "react-dom"
import App from "./app/app.js"
import { makeid } from "shared/services/helpers.js"
import { Provider } from "react-redux"
import store from "./app/services/store.js"
require('./app/scss/main.scss')
window.R_loadReactComment = function(element){
new ReactDOM.render(<Provider store={store}><App /></Provider>, element);
}
In the template file, I can render this app on call like so:
$(function(){
if($(".ordered_react_comment").length){
var elements = document.getElementsByClassName("ordered_react_comment");
for (var x = 0; x < elements.length; x++)
window.R_loadReactComment(elements[x]);
}
})
It renders as expected, but when I click the button to reveal the comment app, all the react instances of this comment app reveal! I'm guessing the most likely reason for this is because they are all sharing and mutating the same store. I don't want this to happen, I want each react app to have its own store. How can I get it so that each app has its own store (if that's the issue here).
Upvotes: 1
Views: 1082
Reputation: 8065
JavaScript modules are singletons. You can read about this more here.
Modules are singletons. Even if a module is imported multiple times, only a single “instance” of it exists.
Because of this import store from "./app/services/store.js"
gives you same store every time.
To avoid this, import a function that creates store instances and, pass an instance to your provider.
As an example currently, your store is probably like this.
// create store
export default store;
you need to wrap this in function and return that function.
function getNewStore() {
// create store
return store
}
export default getNewStore;
Now you can use this function every time to create a new store instance.
import getNewStore from "./app/services/store.js"
//...
window.R_loadReactComment = function(element){
const store = getNewStore();
new ReactDOM.render(<Provider store={store}><App /></Provider>, element);
}
Upvotes: 4