Reputation: 195
I am using react-redux for my app. I am facing a problem. I have the following product reducer, but I do not want to use switch case as the below cases are my different screen of products. On use switch case, the Offers screen is getting empty when I load vegProducts.
//in the productsreducer
const initialState = {};
export const productsReducer = (state = initialState, action) => {
switch (action.type) {
case SET_OFFERS:
return {
offers: action.offers,
};
case SET_VPRODUCTS:
return {
vegProducts: action.vegProducts,
};
case SET_NPRODUCTS:
return {
nvegProducts: action.nvegProducts,
};
}
return state;
};
I am calling different reducers in my App.js as below
import productsReducer from './store/reducers/products';
import cartReducer from './store/reducers/cart';
import ordersReducer from './store/reducers/orders';
const rootReducer = combineReducers({
products: productsReducer,
cart: cartReducer,
orders: ordersReducer,
});
Any help will be greatly appreciated as I have spent almost 3 days searching the internet for solution.
Upvotes: 1
Views: 1066
Reputation: 8273
You should append the data to the state, not replacing it. change it to:
const initialState = {};
export const productsReducer = (state = initialState, action) => {
switch (action.type) {
case SET_OFFERS:
return {
...state, // <--- add this to append offers to state
offers: action.offers,
};
case SET_VPRODUCTS:
return {
...state, // <--- add this
vegProducts: action.vegProducts,
};
case SET_NPRODUCTS:
return {
...state, // <--- add this
nvegProducts: action.nvegProducts,
};
}
return state;
};
To understand how it works:
let state = {a: 1, b: 2} // <-- the state
{...state} // {a: 1, b: 2} <-- spread operator spreads the properties of the object
{b: 3} // {b: 3} <-- currently your doing this
{...state, b: 3} // {a: 1, b: 3} <-- you should instead append b to state, like this
{...state, a: 5} // {a: 5, b: 2} <-- appending a to state
Upvotes: 3