My Redux Store is Like this:
{
data: {
dashboards: {...},
products: {...}
},
globalFilters: {
...
}
}
problem is that when I dispatch dashboards data, fetching data from the backend and update store. Saga:
export function* getDashboards() {
yield takeEvery(constants.GET_DASHBOARDS, function* generator() {
try {
const { data } = yield axios.get('/dashboards', {
params
});
yield put(actions.setDashboards(data));
} catch (e) {
console.log(e);
}
});
export default function* rootSaga() {
yield all([fork(getDashboards)]);
}
reducer:
case constants.SET_DASHBOARDS:
return {
...state,
data: action.payload.data
};
default:
return {
...state
};
all useSelectors are triggered, including useSelectors(state => state.globalFilters) and rerendering all components, which are using any global data. how to solve this?
CodePudding user response:
If your store looks something like this , then you wont face this problem
export const store = configureStore({
reducer: {
data: dataSlice.reducer,
globalFilters: globalFilters.reducer
},
})
CodePudding user response:
The problem is your default reducer - it always creates a new state even if nothing ever changed.
Instead of
return {
...state
};
do
return state
Or, even better, use the official Redux Toolkit to write your reducers - it's the officially recommended standard to write reducers since 2019 and mostly prevents errors such as this, while reducing your code to 1/4. See why Redux Toolkit is how to write Redux today.