This was done the same way in other components, but now it gets confusing for me. Why do we need to clone it here? Why can’t we just target it directly like this.state.errors…
Was hoping someone can help explain a little more.
But in this block of code, from how I understand it its not manipulating any DOM element but rather referencing the error content coming from the server then displaying it on the client side?
As long as it’s “this.state…” it should be spread so as not to change the state directly. Recap using this.state we are still dealing with the state not the server
Again this is misleading. A part of the state is not necessarily prefixed with this.state.:
handleLike = movie => {
const movies = [...this.state.movies];
const index = movies.indexOf(movie);
movies[index].liked = !movies[index].liked;
this.setState({ movies });
};
Here movie[index] points to a movie object in the state although it’s not prefixed with this.state. We need to make a copy first before changing it:
handleLike = movie => {
const movies = [...this.state.movies];
const index = movies.indexOf(movie);
movies[index] = { ...movies[index] };
movies[index].liked = !movies[index].liked;
this.setState({ movies });
};
doSubmit = async () => {
try {
await userService.register(this.state.data);
} catch (ex) {
if (ex.response && ex.response.status === 400) { //Check to see if there is a response, and response status is 400
const errors = { ...this.state.errors }; //clone error object
errors.username = ex.response.data; //get the error from the server
this.setState({ errors }); //then pass this as new errors obj
}
}
};
At first I couldn’t fathom the connection between these 2 lines: