I've a following App.js that correctly sets two states - newName on input change and persons array of objects after the form is submitted.
I can see in the debugger both my states get updated and I want to display persons object values as <li> elements each time new value is added.
import { useState, useEffect } from "react";
const App = () => {
const [persons, setPersons] = useState([{ name: "Arto Hellas" }]);
const [newName, setNewName] = useState("");
const handleNameInput = (e) => {
e.preventDefault();
setNewName(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
setPersons(prevState => [...prevState, {name: newName}])
console.log(persons);
};
return (
<div>
<h2>Phonebook</h2>
<form onSubmit={handleSubmit}>
<div>
name: <input onChange={handleNameInput} />
</div>
<div>
<button type="submit">add</button>
</div>
</form>
<div>debug: {newName}</div>
<h2>Numbers</h2>
<ul>
{useEffect(() => {
Object.values(...persons).map((person, index) => <li key={index}>{person}</li>)
}, [persons])}
</ul>
</div>
);
};
export default App;
I've tried using the following code to render values of objects inside my persons array but that displays nothing and no error is displayed. I've tried using useEffect since state updates are async and I've thought this will fix everything but still nothing gets displayed. Why is the following code not working even though my state gets updated? How else can I display values of an array of objects as list items in React?
{useEffect(() => {
Object.values(...persons).map((person, index) => <li key={index}>{person}</li>)
}, [persons])}