0
votes

I am trying to use axios to make a POST request. Following is my axios function in a file called userFunctions.js.

export const savePost = (postInfo) => {
    return axios
        .post(
            "admin/savepost",
            { first_name: "hello", last_name: "world" },
            {
                headers: {
                    Authorization: `Bearer ${localStorage.usertoken}`,
                },
            }
        )
        .then((response) => {
            console.log(response); //response is able to get printed here
            console.log("axios:: saved post");
        });
};

I'm calling this in another file called card.js shown below:

handleChange(e) {
        e.preventDefault();
        const { name, type, checked } = e.target;
        if (type === "checkbox") {
            this.setState({
                [name]: checked,
            });
            savePost("post 1").then((res) => {
                //response is undefined here!
                console.log(res === undefined); //true

                if (!res.error) {
                    console.log("client: post saved");
                }
            });
        }
    }

and I'm getting the following error:

Unhandled Rejection (TypeError): Cannot read property 'error' of undefined

I don't understand is why the response is able to get printed in the userFunctions.js but is undefined when I call the savePost variable in card.js

1

1 Answers

0
votes

It happens because you handle response in the userFunctions.js and do not return it back(ie last then in your promise chain returns undefined). Make following change:

    .then((response) => {
        console.log(response); //response is able to get printed here
        console.log("axios:: saved post");
        return response
    });