Authentication and Authorization - 3 - Submitting the Registration Form [Question]

Hi Coders!

I’m currently on the lecture about Registration Form.

On the doSubmit() method Mosh cloned the errors object to display an error under the try catch block:

  doSubmit = async () => {
    try {
      await userService.register(this.state.data);
    } catch (ex) {
      if (ex.response && ex.response.status === 400) {
        const errors = { ...this.state.errors };    //<----Clone error object
        errors.username = ex.response.data;
        this.setState({ errors });
      }
    }
  };

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.

Thanks in advance! :raised_hands:

By cloning it, it means we don’t want to modify the DOM directly

Hi Augustine,

Yes, that I understand.

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?

DOM state.

In React we mustn’t change the state directly so it’s not an option to assign a new value to this.state.errors.username.

1 Like

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 });
  };

Thank you both for your time explaining.

I think I get it now:

  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:

const errors = { ...this.state.errors }; 
errors.username = ex.response.data;

That’s nonsense. Spreading creates shallow copies! And you knew that two month ago: