'axios__WEBPACK_IMPORTED_MODULE_0___default.a[method] is not a function
I'm getting above error when I make a request to backend. I have similar code on another project, there is no issue. but here it's causing problems
my code:
import axios from 'axios';
export default function apiCall(method, path, data) {
console.log(method, url, data);
return new Promise((resolve, reject) => {
return axios[method](path, data)
.then(res => {
return resolve(res.data);
})
.catch((err) => {
console.log(err)
reject(err)
});
});
}
api call function
apiCall('POST', `${process.env.REACT_APP_BASE_URL}/`, {standard, subject, totalMarks, totalQuestions} )
.then(data =>{
console.log(data);
})
.catch(err=>{
console.log(err);
return this.props.addError(err.message)
});
Solution 1:[1]
Pay attention to the fact that objects in javascript are case sensitive, therefore, accessing obj['post'] and obj['POST'] will return different values.
axios has method get, post etc, as lowercase, you are trying to access them via uppercase, therefore u getting an undefined value.
You can fix that by converting the method variable to lowercase.
import axios from 'axios';
export default function apiCall(method, path, data) {
return new Promise((resolve, reject) => {
return axios[method.toLowerCase()](path, data)
.then(res => {
return resolve(res.data);
})
.catch((err) => {
console.log(err)
reject(err)
});
});
}
BTW, axios methods are already returning Promises, so you can make your code a bit simpler by using it.
import axios from 'axios';
export default function apiCall(method, path, data) {
return axios[method.toLowerCase()](path, data)
.then(res => res.data)
.catch((err) => {
console.log(err);
return Promise.reject(err);
});
}
Solution 2:[2]
I had the same issue and felixmosh gave me the key
const { data } = await axios.PUT(
`/api/users/profile/update/`,
user,
config
)
I fixed it changing the method and it worked to me ;)
const { data } = await axios.put(
`/api/users/profile/update/`,
user,
config
)
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 | felixmosh |
| Solution 2 | colidom |
