0

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
3
  • If you are trying to create dynamic widgets, then your actions should be dynamic as well, shouldn't they? Commented Oct 29, 2020 at 13:33
  • until now they not. Commented 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. Commented Oct 29, 2020 at 13:53

1 Answer 1

2

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.