Learning React, making a very simple to-do list. I am able to add items as expected. When I input something and click "add", the item shows up on the page. But I noticed that if I try to console.log the result, the array that gets consoled is always missing the last item. Eg. If I enter "bread" and click "add", it will show on the page, but in the console, I just get an empty array. If I then enter "milk" and click "add", on the page both bread and milk show up but in the console, I only see ["bread"] as the array. Why is this happening?
import { useRef, useState } from "react";
export default function App() {
const [items, setItems] = useState([]);
const inputRef = useRef();
function onSubmit(e) {
e.preventDefault();
const value = inputRef.current.value;
setItems(prev => [...prev, value]);
console.log(items);
inputRef.current.value = "";
}
return (
<main>
<form onSubmit={onSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Add</button>
</form>
<h3>My List:</h3>
<ul>
{items.map(item => (
<li>{item}</li>
))}
</ul>
</main>
);
}