The Dead Man
The Dead Man

Reputation: 5566

Display data from jsonplaceholder api using react hooks

I have simple rest api, I am trying to display users from jsonplaceholder fake api

Here is my function component

import React, {useState, useEffect} from "react";
import axios from 'axios';

 export default function TableList() {

  const [data, setData] = useState({ hits: [] });

    useEffect(() => {
      const fetchData = async () => {
        const result = await axios(
          'https://jsonplaceholder.typicode.com/users',
        );
        setData(result.data);
          console.log(result.data);
      };
      fetchData();
    }, []);


  return (
    <div>
      <ul>
            {data.hits.map(item => (
              <li key={item.id}>
              <h1>{item.name}</h1>
              </li>
            ))}
          </ul>

    </div>

  );
}

Unfortunately, I am getting the following error:

TableList.js:22 Uncaught TypeError: Cannot read property 'map' of undefined

What is wrong with my code?

Upvotes: 0

Views: 4971

Answers (2)

Romen Rodr&#237;guez
Romen Rodr&#237;guez

Reputation: 186

"hits" is necesary?.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

export default function MiJSON(){
   const [users, setUsers] = useState([]);
   const urlJson= 'https://jsonplaceholder.typicode.com/users';

    useEffect(()=>{
        const fetchData = async ()=>{
            const users_data = await axios(urlJson);
            setUsers(users_data);
        };
        fetchData();
     },[setUsers])

   console.log(users)

return (
<div>
    <h1>USERS</h1>
  <ul>      
    {(users.length !== 0)
        ?
      users.data.map(item => (
        <li key={item.id}>
          <span>{item.name}</span>
        </li>
      ))
      
      : <h1>Sorry info not found</h1>
    }
  </ul>
</div>
)
}

Upvotes: 1

Duderino9000
Duderino9000

Reputation: 2597

You're setting the data incorrectly and you should null check data.hits. Here's a working example

function TableList() {
  const [users, setUsers] = useState({ hits: [] });

  useEffect(() => {
    const fetchData = async () => {
      const { data } = await axios(
        "https://jsonplaceholder.typicode.com/users"
      );
      setUsers({ hits: data });
    };
    fetchData();
  }, [setUsers]);

  return (
    <div>
      <ul>
        {users.hits &&
          users.hits.map(item => (
            <li key={item.id}>
              <span>{item.name}</span>
            </li>
          ))}
      </ul>
    </div>
  );
}

https://codesandbox.io/s/affectionate-lehmann-17qhw

Upvotes: 3

Related Questions