I am trying to make a unique store value for each instance of a function that is created but for some reason each instance of the function I create is using the same store value.
I am creating a simple store function and then creating the store inside the function. But even though the stores are being created in each instance of the function they are being shared. Why does this happen.
Here is a codesandbox Sandbox
Here is the code
createStore.js
const createStore = (initialState) => {
const state = initialState;
const get = () => state;
const set = (key, value) => (state[key] = value);
return {
get,
set
};
};
export default createStore;
Main function
import createStore from "./createStore";
import initialState from "./initialState";
const controller = () => {
const store = createStore(initialState);
const setStore = (key, val) => store.set(key, val);
const getStore = () => store.get().string;
return {
setStore,
getStore
};
};
export default controller;
Then I am trying to use them by creating multiple instances of the controller like so:
import controller from "./controller";
const ctl1 = controller();
const ctl2 = controller();
ctl1.setStore('string', 'Hello')
ctl2.setStore('string', 'Welcome')
clt1.getStore() // will output the last set store value of ctl2
CodePudding user response:
Looks like the issue is that your initialState
that you are importing is a shared reference which you're using to start your store state. So the issue isn't so much that your store code is decoupled correctly (seems to be) but rather that you're manipulating the same underlying referenced object initialState
.
Fix Approach 1
You can likely fix this by cloning/copying initialState
rather than just directly using its reference.
Here's an example of what that could look like with lodash:
import { cloneDeep } from 'lodash';
/* ... */
const store = createStore(cloneDeep(initialState));
Here is a codesandbox for that approach: https://codesandbox.io/s/modern-frog-npd2w
Fix Approach 2
Another alternative you could consider is to not have a shared singleton module of initialState
and instead have it be a factory function to create that initial state, which would also solve the same issue:
import { createInitialState } from './initialState';
/* ... */
const initialState = createInitialState();
const store = createStore(initialState);
Here's a codesandbox for that approach: https://codesandbox.io/s/charming-greider-5go5t