'TypeError: Cannot read property 'payload' of undefined in React js
an getting an error while while submit the form , error are mentioned below..
TypeError: Cannot read property 'payload' of undefined
if you want any more information tell me
reducer/index.js
export default (posts =[], action) => {
switch(action.type){
case 'FETCH_ALL':
return action.payload;
case 'CREATE':
return [...posts. action.payload];
default:
return posts;
}
}
Actions/posts.js
import * as api from '../api';
//action creators
export const getPosts = () => async (dispatch) => {
try {
const { data } = await api.fetchPosts();
dispatch({ type: 'FETCH_ALL', payload: data })
} catch (error) {
console.log(error.message)
}
}
export const createPost = (post) => async (dispatch) =>{
try{
const {data} = await api.createPost(post);
dispatch({type: 'CREATE', payload:data})
}catch(error){
console.log(error);
}
}
API/index.js
import axios from 'axios';
const url = "http://localhost:7000/posts";
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url,newPost);
Solution 1:[1]
You declared data wrong way.
export default (posts =[], action) => {
switch(action.type){
case 'FETCH_ALL':
return action.payload;
case 'CREATE':
return [...posts. action.payload];
default:
return posts;
}
}
You remove . by ,
case 'CREATE':
return [...posts, action.payload];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
