React map object containing array

Viewed 96

I am building an app which fetches the following JSON response:

{
  "result": [
    {
      "id": 6,
      "name": "Test 1",
      "parent": 5
    },
    {
      "id": 17,
      "name": "Test2",
      "parent": 5
    }
  }
}

I would like to map through the result, and display in an unordered list.

App.js:

function App() {
  const [items, setItems] = useState([]);
  useEffect(() => {
    const searchDB = () => {
      fetch("http://127.0.0.1:8443/subColumns/5/?key=fc257229-8f91-4920-b71f-885403114b35", {
        mode: 'cors',
        credentials: 'include'
      })
        .then(res => res.json())
        .then(
          (json) => {
            setIsLoaded(true);
            setItems(json);
          },
          (error) => {
            setIsLoaded(true);
            setError(error);
          }
        )
    }
    searchDB();
  }, [])

  useEffect(() => {
    console.log(items.result);
  }, [items]);

  return (
    <ul>
      {(Object.entries(items)).map(item => (
        <li key={items.id}>
          {item.id} - {item.name} - {item.parent}
        </li>
      ))}
    </ul>
  );
}

However, the current output shows the map is only running once and displays is as follows:

enter image description here

5 Answers

You don't need object entries, just do:

 <ul>
  {items.result.map(item => (
    <li key={items.id}>
      {item.id} - {item.name} - {item.parent}
    </li>
  ))}
</ul>

Try this approach,

 items.result.map(({id, name, parent}) => 
       <li key={id}>
          {id} - {name} - {parent}
        </li>)

I don't think using map for iteration is a good idea. map is used to iterate and make changes to the array based on its return value. If you simply want to iterate and display items use forEach

Because he interested in the return value in this case a an array of list items `map` is a better fit for this
<ul>
  {items.result.map(item => (
    <li key={items.id}>
      {item.id} - {item.name} - {item.parent}
    </li>
  ))}
</ul>

You will need to create table body like -

render() {

let tableBody = this.items.map((item, index) => (
        <tr key={index} id="one">
               <td>item.id</td>
               <td>item.name</td>
               <td>item.parent</td>
        </tr>
      ));

//And in the render return -
 return (
                 <table>
                   <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Parent</th>
                        </tr>
                   </thead>
                   <tbody>{tableBody}</tbody>
               </table>

  )

}
{(Object.result.entries(items)).map(item => (
        <li key={items.id}>
          {item.id} - {item.name} - {item.parent}
        </li>
      ))}
Related