0

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>
  );
}
2
  • 2
    You are setting the data, the console.log() is just outputting the old data as setState is asyncronous and projectData hasn't changed yet. Commented Sep 16, 2021 at 8:46
  • 1
    To see what happens in real time, just append this somewhere in the page {JSON.stringify(projectData)}. Commented Sep 16, 2021 at 8:49

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.