I am building a react app with multi-widgets using react-redux every widget created dynamically.
I have an issue when update in the widget reflect in all other widgets.
is there any way to handle multi reducer to handle isolated data for every widget?
Reducer
import { combineReducers } from 'redux';
const widgetReducer= (state = {}, action) => {
switch (action.type) {
case 'SET_API':
return { ...state, API: action.payload.API };
}
return state;
}
export default combineReducers({
widget: widgetReducer
});
Actions
export const SetAPI = (data) => {
return {
type: "SET_API",
payload: {
API: data
}
}
}
index.js
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers'
const store = createStore(reducers)
<Provider store={store}><Widget /></Provider>
asked Oct 29, 2020 at 13:29
-
If you are trying to create dynamic widgets, then your actions should be dynamic as well, shouldn't they?Shuvo– Shuvo2020年10月29日 13:33:43 +00:00Commented Oct 29, 2020 at 13:33
-
until now they not.FiryCode– FiryCode2020年10月29日 13:51:58 +00:00Commented Oct 29, 2020 at 13:51
-
@Shuvo I am trying to handle this but I need to figure out what is a good approach for this.FiryCode– FiryCode2020年10月29日 13:53:01 +00:00Commented Oct 29, 2020 at 13:53
1 Answer 1
You can dynamic reducer for each widget is by assigning unique id for each new widget created and creating a new parent reducers as wrapper, something like:
import { combineReducers } from 'redux';
const widgetReducer= (state = {}, action) => {
switch (action.type) {
case 'SET_API':
return { ...state, API: action.payload.API };
}
return state;
}
export widgetsContainerReducer(state = {}, action) {
switch(action.type) {
case 'SET_API':
case 'WIDGET_ACTION_1':
case 'WIDGET_ACTION_2': // other widget specific actions
const widgetId = action.payload.id;
return {
...state,
[widgetId]: widgetReducer(state[widgetId], action)
}}
default:
return state;
}
}
export default combineReducers({
widgets: widgetsContainerReducer
});
Then have a widget id for every action specific to each widget:
export const SetAPI = (widgetId, data) => {
return {
type: "SET_API",
payload: {
API: data,
id: widgetId
}
}
}
Your resulting reducer will look something like this:
{
widgets: {
widget-1: {
API: 'api-1'
},
widget-2: {
API: 'api-2'
},
...
}
}
answered Oct 29, 2020 at 14:40
Comments
lang-js