Home > Software design >  Can you explain the updateForm() function from MongoDB official MERN stack tutorial?
Can you explain the updateForm() function from MongoDB official MERN stack tutorial?

Time:12-03

So, I am following the MERN stack tutorial from the MongoDB official website.

In the create.js file we create the Create component. Follows the code sample:

import React, { useState } from 'react';
import { useNavigate } from 'react-router';

export default function Create() {
  const [form, setForm] = useState({
    name: '',
    position: '',
    level: '',
  });
  const navigate = useNavigate();

  // These methods will update the state properties.
  function updateForm(value) {
    return setForm((prev) => {
      return { ...prev, ...value };
    });
  }

  // This function will handle the submission.
  async function onSubmit(e) {
    e.preventDefault();

    // When a post request is sent to the create url, we'll add a new record to the database.
    const newPerson = { ...form };

    await fetch('http://localhost:5005/record/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(form),
    }).catch((error) => {
      window.alert(error);
      return;
    });

    setForm({ name: '', position: '', level: '' });
    navigate('/');
  }

  // This following section will display the form that takes the input from the user.
  return (
    <div>
      <h3>Create New Record</h3>
      <form onSubmit={onSubmit}>
        <div className="form-group">
          <label htmlFor="name">Name</label>
          <input
            type="text"
            className="form-control"
            id="name"
            value={form.name}
            onChange={(e) => updateForm({ name: e.target.value })}
          />
        </div>
        <div className="form-group">
          <label htmlFor="position">Position</label>
          <input
            type="text"
            className="form-control"
            id="position"
            value={form.position}
            onChange={(e) => updateForm({ position: e.target.value })}
          />
        </div>
        <div className="form-group">
          <div className="form-check form-check-inline">
            <input
              className="form-check-input"
              type="radio"
              name="positionOptions"
              id="positionIntern"
              value="Intern"
              checked={form.level === 'Intern'}
              onChange={(e) => updateForm({ level: e.target.value })}
            />
            <label htmlFor="positionIntern" className="form-check-label">
              Intern
            </label>
          </div>
          <div className="form-check form-check-inline">
            <input
              className="form-check-input"
              type="radio"
              name="positionOptions"
              id="positionJunior"
              value="Junior"
              checked={form.level === 'Junior'}
              onChange={(e) => updateForm({ level: e.target.value })}
            />
            <label htmlFor="positionJunior" className="form-check-label">
              Junior
            </label>
          </div>
          <div className="form-check form-check-inline">
            <input
              className="form-check-input"
              type="radio"
              name="positionOptions"
              id="positionSenior"
              value="Senior"
              checked={form.level === 'Senior'}
              onChange={(e) => updateForm({ level: e.target.value })}
            />
            <label htmlFor="positionSenior" className="form-check-label">
              Senior
            </label>
          </div>
        </div>
        <div className="form-group">
          <input
            type="submit"
            value="Create person"
            className="btn btn-primary"
          />
        </div>
      </form>
    </div>
  );
}

I have difficulty to decode what updateForm() does exactly

function updateForm(value) {
    return setForm((prev) => {
      return { ...prev, ...value };
    });
  }

My questions are:

  1. What is the value of prev parameter? I don't understand how this works as we don't place any value in this parameter.
  2. How setForm() manipulates { ...prev, ...value }. Why couldn't we use setForm({ value }) instead?

CodePudding user response:

The updateForm function is used to update the form state variable in the Create component. This form state variable is an object that contains the values of the input fields in the form (i.e. the name, position, and level of the person being added).

The updateForm function takes in a value, which is an object containing the updated values for one or more of the properties in the form state variable. The updateForm function then creates a new object that is a copy of the existing form state variable, and updates the copied object with the values passed in to the function.

Here is an example of how the updateForm function might be used:

// Update the form state variable with a new name value
updateForm({ name: 'John Doe' });

// The form state variable now looks like this:
{
  name: 'John Doe',
  position: '',
  level: '',
}

The updateForm function is used in the onChange event handlers for each of the input fields in the form. When the user updates the value of an input field, the updateForm function is called with the updated value for that field, which updates the form state variable with the new value.

For example, when the user updates the name field in the form, the updateForm function is called with the updated name value, and the form state variable is updated with the new name value:

// User updates the name field in the form to 'John Doe'
onChange={(e) => updateForm({ name: e.target.value })}

// The updateForm function is called with the updated name value
updateForm({ name: 'John Doe' });

// The form state variable now looks like this:
{
  name: 'John Doe',
  position: '',
  level: '',
}

The updateForm function is used to keep the form state variable up-to-date with the latest values entered by the user in the form. When the user submits the form, the values in the form state variable are used to create a new record in the database.

CodePudding user response:

As for your first question - you can use setState in 2 ways:

  1. pass value of the new state.
  2. pass a callback with argument of the current state, that returns the new state value.

Your second question has nothing to do with react but with JavaScript. it's just a way to merge 2 object, but the duplicate keys will be overridden by the latest value.

The ... is the spread operator .

let obj1 = {
  a: 2,
  b: 4,
  c: 6
};
let obj2 = {
  c: 8,
  d: 0
};

console.log({ ...obj1,
  ...obj2
});

  • Related