Bnar Kamal
Bnar Kamal

Reputation: 1

React state array (first input not working)

why I can't set the Data in the 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>
  );
}

Upvotes: 0

Views: 669

Answers (2)

Abhinav Raut
Abhinav Raut

Reputation: 1

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]);

Upvotes: 0

hgb123
hgb123

Reputation: 14871

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

Upvotes: 1

Related Questions