Home > OS >  React state array (first input not working)
React state array (first input not working)

Time:09-16

why I cant set the Data in first Click i Have to input twice to set the data. Thanks for your help....

export default function App() {
  const [title, setTitle] = useState();
  const [projectData, setProjectData] = useState([]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setProjectData([...projectData, { projectTitle: title }]);
    console.log(projectData);
  };
  return (
    <div className="App">
      <input
        type="text"
        onChange={(e) => {
          setTitle(e.target.value);
        }}
      />
      <button onClick={handleSubmit}>insert</button>
    </div>
  );
}

CodePudding user response:

Actually it did, but the setState hook runs asynchronously so the console.log after that won't reflect the change. You could use useEffect to watch for the change of projectData instead

import React, { useEffect, useState } from "react";

export default function App() {
  const [title, setTitle] = useState();
  const [projectData, setProjectData] = useState([]);

  useEffect(() => {
    console.log(projectData);
  }, [projectData]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setProjectData([...projectData, { projectTitle: title }]);
  };
  return (
    <div className="App">
      <input
        type="text"
        onChange={(e) => {
          setTitle(e.target.value);
        }}
      />
      <button onClick={handleSubmit}>insert</button>
    </div>
  );
}

Edit red-leaf-lez7s

CodePudding user response:

In React setState actions are asynchronous and are batched for performance gains. This is explained in the documentation of setState. If you want to log projectData you can use useEffect hook.

const handleSubmit = (e) => {
  e.preventDefault();
  setProjectData([...projectData, { projectTitle: title }]);
};
  
// useEffect with ProjectData as dependency 
useEffect(() => {
   console.log(projectData);
}, [projectData]);
  • Related