Search code examples
javascriptreactjsreduxaxiosredux-form

axios doesn't get post request in redux-form


I have this code:

import axios from 'axios'

const storeDevices = values => {
    axios.create({
        baseURL: 'http://localhost:8000/something/store',
        method: 'POST',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: values
    });
}

export default storeDevices;

The following code is correct because it returns an object with all data from my form

const storeDevices = values => {
    console.log(values);
}

export default storeDevices;

Interestingly if I try to use .then I have an error:

axios__WEBPACK_IMPORTED_MODULE_0___default.a.create(...).then is not a function

Code with .then

axios.create({
    baseURL: 'http://localhost:8000/something/store',
    method: 'POST',
    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
    data: values
}).then(res => {
    console.log(res);
    console.log(res.data);
});

Solution

  • It's because you've never told axios to send a POST request. axios.create creates a new instance of axios with a custom config. This instance have different methods (like .get(), .post(), etc.), none of which is then(), so that's why you received the error .then is not a function. You set the default method to POST but you've never sent a request.

    I think you wanted to create this new instance because you didn't want to add the base URL and headers every single time. If you want to create a base instance, you can assign the returned value to a new variable:

    const API = axios.create({
      baseURL: 'http://localhost:8000/api/',
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
    });
    

    And use this instance to post your request:

    API.post('store', data)
      .then(res => {
        console.log(res);
        console.log(res.data);
    });