I want to add items in the object in the redux store one after the other as the user progresses in the application. Therefore, I want to add items in the store without removing the previous items in the store.
Please refer the code below:
Code for the reducer:
const currentTravelPlanDefaultState = {};
export default (state = currentTravelPlanDefaultState, action) => {
switch(action.type){
case 'ADD_PLAN':
return {
...state,
currentTravelPlan: {
...state.currentTravelPlan,
...action.currentTravelPlan
}
}
default:
return state;
}
};
Code for the action:
import uuid from 'uuid';
export const addTravelPlan = (details) => ({
type: 'ADD_PLAN',
currentTravelPlan: {
id: uuid(),
details
}
});
Code for the disptach calls:
store.dispatch(addTravelPlan({destination: 'Cuba'}));
store.dispatch(addTravelPlan({hotel: 'Cuba Grand'}));
store.dispatch(addTravelPlan({travelMode: 'AirWays'}));
However, it appears that only the last item is added in the store which is the airways and the previous items are not persisted.
Please help!
Thanks in advance.
I assume you want your data to look like this after the dispatch calls:
currentTravelPlan: {
id: uuid(),
destination: 'Cuba',
hotel: 'Cuba Grand',
travelMode: 'Airways'
}
In that case, your action code should be:
export const addTravelPlan = (details) => ({
type: 'ADD_PLAN',
currentTravelPlan: {
id: uuid(),
...details
}
});
and your reducer:
const currentTravelPlanDefaultState = {};
export default (state = currentTravelPlanDefaultState, action) => {
switch(action.type){
case 'ADD_PLAN':
return {
...state,
...action.currentTravelPlan
}
default:
return state;
}
};