0

I have created a basic form:

enter image description here

On form submit, I'm converting the time from hours to minutes (if in minutes) but the problem is that state is not updating, as you can see Old Object and New Object.

This is the function in which I'm performing the update:

  const onFormSubmit = (event) => {
    event.preventDefault();
    const updatedObject = {
      name: newMovie.name,
      ratings: newMovie.ratings,
      duration: parseDuration(newMovie.duration),
    };
    console.log("Old object", newMovie);
    setNewMovie(updatedObject);
    console.log("New object", newMovie);

    if (updatedObject.duration != 0) {
      props.onNewMovieInput(newMovie);
    }
  };

This is the initial state:

const [newMovie, setNewMovie] = useState();
  const [durationError, setDurationError] = useState(false);
  const onDataUpdate = (event) => {
    const key = event.target.id;
    const value = event.target.value.trim();

    setNewMovie((prevState) => {
      return { ...prevState, [key]: value };
    });
  };

Where onDataUpdate is called on every onChange event.

Ashar
  • 724
  • 10
  • 30
  • `onFormSubmit` attempts to use `newMovie` before the state will have been updated. `setState` is async (not in the sense that you can `await` it, however). – Dave Newton Mar 28 '22 at 15:58
  • You cannot use the updated state during the same render cycle as the one you update it. Please see the linked duplicate for more details. – Brian Thompson Mar 28 '22 at 15:59
  • @BrianThompson AS per the link, solution is to use useEffect, however, how I can use in my case is a bit difficult for me. Because useEffect cannot be used inside a function and I want to update the state when onFormSubmit invokes. Can you help me how I can achieve this? – Ashar Mar 28 '22 at 16:04
  • 1
    You are updating the state, you just can't use it yet. `updatedObject` holds the values you need, just continue using it - `props.onNewMovieInput(updatedObject);` – Brian Thompson Mar 28 '22 at 16:07

0 Answers0