I want to build a central ajax handler for all of my requests, inside my React app. It has nothing to do with Redux or anything similar. It's just a "central junction" for performing ajax requests, from React components.
The thing is, that i want to be able to intercept certain errors, to avoid repeating it in every ajax call. Eventually, i want to call then() again, from the component that actually initiated the request
This is what i have done:
import axios from 'axios';
import handleError from './error';
export default (endPoint, method = 'get', data) => {
return axios({
url: window.BASE_API + endPoint,
method,
data
}).then(({ data }) => {
if (data.status !== 'ok') {
handleError(data.errorMessage);
}
}).catch((error) => {
handleError(error);
})
}
In the react component:
import ajax from '../../services/ajax';
componentDidMount() {
ajax('/content')
.then(({ data }) => {
this.setState(() => ({ pages: data.content }))
})
}
This results in an error: Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
How can i handle the promise twice?
EDIT: this is how my response object looks like:
{content: Array(18), status: "ok", errorMessage: null, metaData: null}