I am writing applications in spring boot and react. I am running a server and want to submit a form from the client side. The form should be saved in the database.
I fill out the form and it is saved in the database, but after filling out the form and clicking the "submit" button the page should switch to the main screen of the application, i.e. the /dashboard
address, but I still stay with the form and when I enter the devtools I get a ERROR: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data').
That is, it comes out that the application itself works, the data is transferred between the client and the server and stored in the database. So the problem lies on the frontend side, specifically on the react side. The message also points to the specific file where the problem is , namely in the file projectActions.js
However, I do not know too much about what the problem is specifically, where I made a mistake, that the page after submitting the form is not "reloaded" and returns to the specified address.
Below I send the class referenced in the error.
I also provide the versions of the packages I use:
"axios": "^0.27.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.0.2",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1"
projectActions.js
import axios from "axios";
import { GET_ERRORS } from "./types";
export const createProject = (project, history) => async (dispatch) => {
try {
const res = await axios.post("http://localhost:8080/api/project", project);
history.push("/dashboard");
} catch (error) {
dispatch({
type: GET_ERRORS,
payload: error.response.data,
});
}
};
CodePudding user response:
Your problem is inside catch
block, you are trying to read error.response.data
, and problem is because there is no response
attribute on error, it is undefined, and when you try to read data
on undefined you will end up with this error.
Depending on error type error
will have different structures. Please read this to get idea how to handle axios error(you need safe checks): axios-error-handling
CodePudding user response:
problem is at
payload: error.response.data,
if you are sure that most of your error has this structure, you can use payload: error?.response?.data .
Keep in mind, I really didn't see a error.response.data structure in an error message before. So it is best you change the way you handle the error.