0

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])}
1
  • Map through the elements and remove the useEffect there, an example has been provided below. Commented Jan 11, 2023 at 22:38

1 Answer 1

1

No need for a useEffect at all, just do

{persons.map((person, index) => (
    <li key={index}>{person}</li>
)}

Also, state updates are not "async", they simply trigger a new render with the updated value, so you can simply use the state value in the function and it will just work.

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

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.