1 year ago

#271450

test-img

Ashar

React: TypeError: null is not an object (evaluating 'event.target.id')

I'm trying to save form input into the state object.

const [newMovie, setNewMovie] = useState({
    name: "",
    ratings: "",
    duration: "",
  });

const handleChangeEvent = (event) => {
    console.log(event.target.value);
    setNewMovie((prevState) => {
      return { ...prevState, [event.target.id]: event.target.value };
    });
    console.log(newMovie);
  };

This is called for this form:

    <form onSubmit={handleFormSubmit}>
      <div className="layout-column mb-15">
        <label htmlFor="name" className="mb-3">
          Movie Name
        </label>
        <input
          type="text"
          id="name"
          placeholder="Enter Movie Name"
          data-testid="nameInput"
          value={newMovie.name}
          onChange={handleChangeEvent}
        />
      </div>
      <div className="layout-column mb-15">
        <label htmlFor="ratings" className="mb-3">
          Ratings
        </label>
        <input
          type="number"
          id="ratings"
          placeholder="Enter Rating on a scale of 1 to 100"
          data-testid="ratingsInput"
          value={newMovie.ratings}
          onChange={handleChangeEvent}
        />
      </div>
      <div className="layout-column mb-30">
        <label htmlFor="duration" className="mb-3">
          Duration
        </label>
        <input
          type="text"
          id="duration"
          placeholder="Enter duration in hours or minutes"
          data-testid="durationInput"
          value={newMovie.duration}
          onChange={handleChangeEvent}
        />
      </div>
    </form>

Issue is as soon as I start typing, right after the first word, React throws the error: "TypeError: null is not an object (evaluating 'event.target.id')" and a couple warnings pop up:

enter image description here

The exact error is as follows. I'm not sure why this is happening because the id parameter is clearly defined in the form. Can anyone help me fix this problem?

enter image description here

Update 1

Logging the entire event.target shows that "id" parameter is present (as per my understanding):

enter image description here

Update 2

Tried extracting the keys and value prior to calling the set state function but now I'm unable to enter anything in the input fields. Please note: It says that "myKey" is not used anywhere despite the fact that I'm literally using it inside the update state function.

Browser logs:

enter image description here

enter image description here

javascript

reactjs

use-state

stateful

0 Answers

Your Answer

Accepted video resources