0

On first submit, it just shows the fields without values, while returns values on the second submit hit on console log.

import React, { useState } from "react";

const Movieform = ({ setMovArray }) => {
  const [movieName, setMovieName] = useState("");
  const [ratings, setRatings] = useState("");
  const [duration, setDuration] = useState("");

  const movArray = [
    {
      name: movieName,
      rating: ratings,
      duration: duration,
    },
  ];

  const [movieData, setMovieData] = useState(movArray);

  const HandleSubmit = (e) => {
    e.preventDefault();

    setMovieData(movArray);
    console.log(movieData);

  };

1 Answers1

0

I'm assuming you initially assign the state as an empty string, and during the first render of the component, the movArray constant takes empty strings into values.

You can do this for example:

  const [movieName, setMovieName] = useState("");
  const [ratings, setRatings] = useState("");
  const [duration, setDuration] = useState("");
  const [movieData, setMovieData] = useState([]);


  const HandleSubmit = (evt) => {
    evt.preventDefault();

    // When submitting the form, we collect fresh values
    const movieData = [{
      name: movieName,
      rating: ratings,
      duration: duration,
    }];

    // And add a fresh array to the state
    setMovieData(movieData);
  };

I also hope that you made a controlled input in the form so that a fresh state is saved for each change

  const [state, setState] = useState("");

  <input
    onChange={evt => setState(evt.target.value)} // fires on each character input and saves the new state
    value={state} // always unique state
  />

The code above will help you )

And in addition you can make one state for your form

  const [movieData, setMovieData] = useState([]);

  // all the object you need is in the state
  const [formState, setFormState] = useState({  
    name: '', rating: '', duration: ''        
  });

  const HandleSubmit = (evt) => {
    evt.preventDefault();
    setMovieData([formState])
  };


  // In JSX
  <input
    name='duration'
    onChange={evt => setFormState({ ...formState, duration: evt.target.value })} // overwrite the data by changing the field we need
    value={formState.duration}
  />
Vadim
  • 1