showing results for - "redux multiple instances of same component"
Cristina
27 Jan 2019
1//You need to implement some way of namespacing the instances. This can be as basic as passing in a key to differentiate the components and reducers.
2
3//You can use the ownProps in your mapStateToProps function to guide the mapping to a namespace
4
5const mapStateToProps = (state, ownProps) {
6    let myState = state[ownProps.namespace]
7    return {
8        myState.value
9    }
10}
11//The same method can be used to pass on a namespace to the mapDispatchToProps
12
13const mapDispatchToProps = (dispatch, ownProps) {
14    return {
15        myAction: (myParam) => dispatch(myAction(ownProps.namespace, myParam))
16    }
17}
18//Just remember to use the namespace in the action type so the reducers don't tread on toes
19
20const myAction => (namespace, myParam) {
21    return { type: `${namespace}/${MY_TYPE_CONSTANT}`, myParam }
22}
23//And make sure the reducer is namespaced too
24
25const myReducer = (namespace) => (state = initialState, action) => {
26    switch(action.type) {
27        case `${namespace}/${MY_TYPE_CONSTANT}`:
28            return { ...state, action.myParam }
29        default:
30            return state
31    {
32}
33//Now add the 2 namespaced reducers when combining reducers
34
35combineReducers({
36    myInstance1 : myReducer('myInstance1')
37    myInstance2 : myReducer('myInstance2')
38}
39//Finally pass the namespace to each instance
40
41render() {
42    return (
43        <div>
44            <MyComponent namespace='myInstance1' />
45            <MyComponent namespace='myInstance2' />
46        </div>
47    )
48}