where am i missing? please help in sorting this out _/_ i have trouble in updating the redux store state correctly without breaking
This is my current state in redux store state before posting the data
next state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": null,
"isLoading": false,
"posts": Array [
Object {
"__v": 0,
"_id": "5f37c3ebc8cb6a46c89bc33c",
"by": Object {
"_id": "5ed8d7fcfd3da42bc426992a",
"name": "mad",
"username": "mad",
},
"content": "this is first post",
"contentWarn": false,
"createdAt": "2020-08-15T11:15:55.986Z",
"flaged": false,
"heading": "first pot",
"report": 0,
"updatedAt": "2020-08-15T11:15:55.986Z",
},
],
},
}
then add new post action is performed using reducer====>
export const posts = (
state = { isLoading: true, errMess: null, posts: [] },
action
) => {
switch (action.type) {
case ActionTypes.UPDATE_POSTS:
return {
posts: state.posts.posts.concat(action.payload),
};
default:
return state;
}
};
this is the error returned
action Object {
"payload": [TypeError: undefined is not an object (evaluating 'state.posts.posts.concat')],
"type": "UPDATE_POSTS_FAILED",
}
undefined is not an object (evaluating 'state.posts.posts.concat')
* Redux\posts.js:24:13 in posts
this is the result i wanted to happen
next state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": null,
"isLoading": false,
"posts": Array [
Object {
"__v": 0,
"_id": "5f37c3ebc8cb6a46c89bc33c",
"by": Object {
"_id": "5ed8d7fcfd3da42bc426992a",
"name": "mad",
"username": "mad",
},
"content": "this is first post",
"contentWarn": false,
"createdAt": "2020-08-15T11:15:55.986Z",
"flaged": false,
"heading": "first pot",
"report": 0,
"updatedAt": "2020-08-15T11:15:55.986Z",
},
Object {
"__v": 0,
"_id": "5f37c3ebc8cb6a46c89bc33c",
"by": Object {
"_id": "5ed8d7fcfd3da42bc426992a",
"name": "mad",
"username": "mad",
},
"content": "this is second post",
"contentWarn": false,
"createdAt": "2020-08-15T11:15:55.986Z",
"flaged": false,
"heading": "second post",
"report": 0,
"updatedAt": "2020-08-15T11:15:55.986Z",
}
],
},
}
Your reducer should have this structures with two level posts:
export const posts = (
state = {
highlights: {
errMess: null,
highlights: [],
isLoading: true,
},
posts: { isLoading: true, errMess: null, posts: [] },
},
action
) => {
switch (action.type) {
case ActionTypes.UPDATE_POSTS:
return {
...state,
posts: state.posts.posts.concat(action.payload),
};
default:
return state;
}
};
and try to keep the same data structure in the state, like highlights !
return {
...state,
posts: state.posts.concat(action.payload),
}
this reducer worked Note: I am using highlight reducer in separate file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.