jakchang
jakchang

Reputation: 452

how can I get result axios post in react?

I'm changing fetch to axis for http library. so I changed some codes, and got one error. the insert request is working well, but the respone at reactjs is error. how can I solve this?

mycode

handleFormSubmit=(e)=>{
        e.preventDefault()
        this.addCustomer()   //here is the part of the error
        .then((response)=>{
            console.log(response.data);
            this.props.stateRefresh();
        })

        this.state = {
            username:"",
            birthday:"",
            gender:"",
            job:"", 
        }

    }

    addCustomer = async()=>{
        const url = '/api/customers';

        const formData = new FormData();
        //formData.append('image',this.state.file);
        formData.append('name',this.state.username);
        formData.append('birthday',this.state.birthday);
        formData.append('gender',this.state.gender);
        formData.append('job',this.state.job);

        return axios.post(url, formData) 
        .then( response => { })
        .catch( error => { console.log('failed', error) })

    }

error

Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
(anonymous function)
src/components/CustomerAdd.js:37
  34 | e.preventDefault()
  35 | this.addCustomer()
  36 | .then((response)=>{
> 37 |     console.log(response.data);
     | ^  38 |     this.props.stateRefresh();
  39 | })
  40 | 

Upvotes: 0

Views: 130

Answers (3)

Daniel Adepoju
Daniel Adepoju

Reputation: 821

Your add customer method is not returning a promise and. then wouldn't work on it. Kindly refactor to look like this:

addCustomer = () => { 
//other codes
return new Promise((resolve, reject) => {
    axios
      .post(url, formData)
      .then(response => resolve(response))
      .catch(error => {
        reject(error);
      });
  });
};

this.addCustomer.then(response => console.log(response.data)).catch(err => console.log(err))

or

just return axios.post(url, formData) and you'll be fine since axios already returns a promise

Upvotes: 0

Nico Gräf
Nico Gräf

Reputation: 246

Your then() in the addCustomer function is kind of deleting the response

return axios.post(url, formData)
  .then( response => { }) // returning an empty object instead of the response
  .catch( error => { console.log('failed', error) })

try

await axios.post(url, formData)
      .catch( error => { console.log('failed', error) })

or without the async:

return axios.post(url, formData)
          .catch( error => { console.log('failed', error) })

Upvotes: 0

Arnaud Christ
Arnaud Christ

Reputation: 3551

This is because you are already catching the success case of your Promise in addCustomer when doing .then( response => { })

Simply remove this line and you should be fine. (Considering that your API is indeed returning something for a POST request)

Upvotes: 1

Related Questions