I'm currently building out a Redux application sort of like Reddit. To learn about state management.
I have now come across an issue I can't get my head around, when I vote on a post I can see the UI changing(+1/-1 vote) but just a second late in prompt with an error.
Unhandled Rejection (TypeError): Cannot read property 'id' of undefined
My component is structured as following
export const submitPostVote = (option, id) => {
return axios.post(`${API_URL}/posts/${id}`, {option}, { headers })
}
export function postPostVote(option, id) {
const request = API.submitPostVote(option, id)
return (dispatch) => {
request.then(({data}) => {
dispatch({type: SUBMIT_POST_VOTE, payload: data})
});
};
}
export default function(state = {}, action) {
const {payload} = action
switch (action.type){
case SUBMIT_POST_VOTE:
return {...state, [payload.data.id]: payload.data}
import { postPostVote } from '../actions';
<span
className='fa fa-angle-up voteArrow'
onClick={() => this.props.postPostVote('upVote', id)}
></span>
export default connect(null, {postPostVote})(PostComponent);
So I'm trying to pass along the option
(upVote || downVote) as well as an id but I cant understand why it returns the error after a can see the change
Much Appreciated, Petter
It looks like you've got a mismatch between how you're defining fields in the action, and using the action in the reducer.
You're defining your action as {type: SUBMIT_POST_VOTE, payload: data}
, but in the reducer, using action.payload.data.id
. I assume that payload.data
won't actually exist, and what you really need is action.payload.id
.