0

So I'm making a simple CRUD app trying to familiarize myself with redux. Basically I'm transferring data from a form and sending a post request to the server to create a new blog post (more or less). Here's the code for the onSubmit:

const handleSubmit = (e) => {
        e.preventDefault()
        dispatch(createPost(postData));
    }

Here's the action being dispatched and where the error is coming from (src/actions/posts.js):

export const createPost = (post) => async (dispatch) => {
    try 
    {
        const { data } = await api.createPost(post);
        dispatch({ type: "CREATE", payload: data});
    } 
    catch (error) 
    {
        console.log(error.message);
    }
}

This function isn't able to destructure data from the api's response, because the response is undefined. Here's the code that sends the request from src/api/index.js:

export const createPost = (newPost) => {
   axios.post(url, newPost);
}

When I console.log the response from this function using .then(), it returns a 201 along with exactly what one would expect from a successful request. So the response returns 201 and the entry gets added to the DB but my action function cannot destructure the data from the response because it's undefined. What is my stupid mistake?

Logan F
  • 9
  • 1
  • Does this answer your question? [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) – Emile Bergeron Dec 29 '21 at 21:23

1 Answers1

3

You aren't returning a value from the function. Try

export const createPost = (newPost) => {
    return axios.post(url, newPost);
}
first last
  • 396
  • 2
  • 5
  • this worked, and I was able to destructure the response. However my store seems to be adding undefined objects to the array even though the action's payload now contains the proper data. Here's my reducer for this case: `return [...posts, action.paylaod];`. No breaks, proper default case returning state, initial state is empty array. – Logan F Dec 29 '21 at 22:41
  • @LoganF Typo in the word "payload"? – timotgl Dec 31 '21 at 10:46