I am working on a backend API and the React frontend that calls the API is randomly getting a Network Error or Cannot read properties of undefined (reading 'data'). I have been unable to reproduce this behavior. It is being reported in the logs for the frontend and it is not showing up in the logs for the backend so as far as I can tell the request is not even hitting the API. The frontend is using Axios for the API calls. Below is an example of the two calls that are getting these errors. Anything in this code that could be causing these errors?
const params = `email=${this.queryParams.email}`;
const response = await axiosStore.axiosApi.get(`/data?${params}`).catch(error => {
console.error(error);
});
const values = await response.data;
this.setValues(values);
const response = await axiosStore.axiosApi.post(`/data`, { data: mappedChanges }).catch(error => {
if (error && error.response && error.response.data && error.response.data.errors) {
const { errors } = error.response.data;
const message = Object.keys(errors)
.map(x => errors[x])
.join(', ');
throw new Error(message);
} else {
throw new Error('Something went wrong');
}
});
newObject = response.data;
CodePudding user response:
Well, I guess that because you mix await and catch could make error append. If there is an error in your call. You catch it then the response object might be undifined. Then when you try to get data from response you’ll get this error. And I’m not sure that you need to call await on response.data. Are you sure it’s a promise? If I was you, I would wrap the calls into a try catch to make things easier to debug
const getStuff1 = async () => {
const params = `email=${this.queryParams.email}`;
try {
const response = await axiosStore.axiosApi.get(`/data? ${params}`);
const values = response.data;
this.setValues(values);
} catch(error) {
console.error(error);
}
};
const getStuff2 = async () => {
try {
const response = await axiosStore.axiosApi.post(`/data`,
{ data: mappedChanges }
);
newObject = response.data;
} catch(error) {
if (error?.response?.data?.errors) {
const { errors } = error.response.data;
const message = Object.keys(errors)
.map(x => errors[x])
.join(', ');
// Do something with error
} else {
// Do something with error
}
}
};
