0

I would like the updated state of the array to be written to the console on the first click. I know that this is done through a callback, but I just can’t understand and find someone to do this in functional components. I would like the updated state of the array to be written to the console on the first click. I know that this is done through a callback, but I just can’t understand and find someone to do this in functional components.

import "./App.css";
import { useState } from "react";

function App() {
  const [name, setName] = useState("");
  const [array, setArray] = useState([]);

  function createNameList(e) {
    setArray((array) => [...array, e]);
    console.log(array);
  }

  return (
    <div className="App">
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <button onClick={createNameList}>accept</button>
    </div>
  );
}

export default App;
qweqwe
  • 19
  • 2
  • code just for visibility – qweqwe Aug 06 '22 at 13:16
  • You can't. To log the updated state, use `useEffect` hook: `useEffect(() => console.log(array), [array])` – Yousaf Aug 06 '22 at 13:17
  • 1
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – David Aug 06 '22 at 13:17
  • with the console, everything is more or less clear, but if I draw this data on the screen? – qweqwe Aug 06 '22 at 13:33

0 Answers0