I am doing pagination where i will be getting data for each page click.I want to append the data with the previous values.Here is my current code.Have no idea to do it.
const InitialProjects={
projectList:[],
error:null,
loading:false
}
export const projects=(state=InitialProjects,action)=>{
switch(action.type){
case ActionTypes.FETCH_PROJECTS:
return Object.assign({},state,{
projectList:[],error:null,loading:true
})
case ActionTypes.FETCH_PROJECTS_SUCCESS:
return {
projectList:action.payload
}
case ActionTypes.FETCH_PROJECTS_FAILURE:
return Object.assign({},state,{
projectList:["not-found"],error:action.payload.message||action.payload.status,loading:false
})
default:
return state;
}
}
My first response will look something like this
[
{
Id:0,
Name:india
},
{
Id:1,
Name:bang
},
{
Id:3,
Name:us
},
{
Id:5,
Name:uk
}
]
second response will be like this
[
{
Id:8,
Name:india
},
{
Id:12,
Name:bang
},
{
Id:19,
Name:us
},
{
Id:35,
Name:uk
}
]
Please do note that the id field might not be consecutive. I want something like this in my redux
projectList:
0(pin): {Id:1,Name:'dewd'}
1(pin): {Id:2,Name:'tyytg'}
2(pin): {Id:5,Name:'xsx'}
3(pin): {Id:4,Name:'tyyt'}
4(pin): {Id:10,Name:'xsx'}
5(pin): {Id:17,Name:'xsx'}
Appreciate any help.Thanks
You can spread the results on each success.
case ActionTypes.FETCH_PROJECTS:
return {
...state,
error: null,
loading: true,
}
case ActionTypes.FETCH_PROJECTS_SUCCESS:
return {
...state,
projectList: [...state.projectList, ...action.payload]
}
Looks like the object spread operator doesn't work in your case. So an ES5 version of the answer for you would be.
case ActionTypes.FETCH_PROJECTS_SUCCESS:
return Object.assign(
{},
state,
{
projectList: state.projectList.concat(action.payload)
});
This copies all the previous values from state into a new object by using Object.assign then overwrites a new projectList property by concatenating old values from state.projectList and new ones from action.payload.
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With