skip to Main Content

I am creating a table and fetching data using Axios. However, I am not able to print the data – when I check, the data is being printed in the browser, but I am not able to print the particular data to a table format.

What should I change in my code?

import { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Table } from "react-bootstrap";
import axios from "axios";
export default function App() {
  const [user, setUser] = useState([]);
  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users", (req, res) => {
        res.json();
      })
      .then((data) => setUser({ ...user, data }))
      .catch((error) => console.error(error));
  });

  return (
    <div className="App">
      <h3 className="text-primary">User List</h3>
      <Table
        variant="danger"
        striped
        bordered
        hover
        className="shadow-lg text-center"
      >
        <thead>
          <tr>
            <th>id</th>
            <th>Name</th>
            <th>UserName</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          {user?.data?.length > 0 &&
            user.data.map((user) => {
              return (
                <tr key={user.id}>
                  <td>{JSON.stringify(user.data["data"].id)}</td>
                  <td>{JSON.stringify(user.data["data"].name)}</td>
                  <td>{JSON.stringify(user.data["data"].username)}</td>
                  <td>{JSON.stringify(user.data["data"].email)}</td>
                </tr>
              );
            })}
        </tbody>
      </Table>
      {/* <div>{JSON.stringify(user.data["data"])}</div> */}
    </div>
  );
}

3

Answers


  1. for example

    import { useEffect, useState } from "react";
    import "bootstrap/dist/css/bootstrap.min.css";
    import { Table } from "react-bootstrap";
    import axios from "axios";
    
    export default function App() {
      const [user, setUser] = useState([]);
    
      useEffect(() => {
        axios
          .get("https://jsonplaceholder.typicode.com/users")
          .then((res) => {
            setUser(res.data);
          })
          .catch((error) => console.error(error));
      }, []);
    
      return (
        <div className="App">
          <h3 className="text-primary">User List</h3>
          <Table
            variant="danger"
            striped
            bordered
            hover
            className="shadow-lg text-center"
          >
            <thead>
              <tr>
                <th>id</th>
                <th>Name</th>
                <th>UserName</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody>
              {user?.length > 0 &&
                user.map((userData) => {
                  return (
                    <tr key={userData.id}>
                      <td>{userData.id}</td>
                      <td>{userData.name}</td>
                      <td>{userData.username}</td>
                      <td>{userData.email}</td>
                    </tr>
                  );
                })}
            </tbody>
          </Table>
          {/* <div>{JSON.stringify(user)}</div> */}
        </div>
      );
    }
    
    Login or Signup to reply.
  2. Replace the useEffect code as follow.

    useEffect(() => {
        axios
          .get("https://jsonplaceholder.typicode.com/users")
          .then((data) => setUser({ ...user, data }))
          .catch((error) => console.error(error));
      }, []);
    
    Login or Signup to reply.
  3. You already know that calling this api will give you an array of users so you can initialise the state as empty array as:

    const [users, setUsers] = useState([]);
    

    and when you are using axios then you don’t have to use res.json(). axios will do it for you out of the box.

    axios
          .get("https://jsonplaceholder.typicode.com/users")
          .then(({ data }) => setUsers(data))
          .catch((error) => console.error(error));
    

    so, after getting data using get method of axios it will return you a promise and you can get data from its data property that is passed an first args. You can directly set state which will be an array of objects.

    .then(({ data }) => setUsers(data))
    

    Here I’ve destructed the object to get only the data property.


    Since users will be an array of objects, so you don’t have to do any check. You can directly use user.id to get the respective property.

    Codesandbox link

    export default function App() {
      const [users, setUsers] = useState([]);
    
      useEffect(() => {
        axios
          .get("https://jsonplaceholder.typicode.com/users")
          .then(({ data }) => setUsers(data))
          .catch((error) => console.error(error));
      }, []);
    
      return (
        <div className="App">
          <h3 className="text-primary">User List</h3>
          <Table
            variant="danger"
            striped
            bordered
            hover
            className="shadow-lg text-center"
          >
            <thead>
              <tr>
                <th>id</th>
                <th>Name</th>
                <th>UserName</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => {
                return (
                  <tr key={user.id}>
                    <td>{user.id}</td>
                    <td>{user.name}</td>
                    <td>{user.username}</td>
                    <td>{user.email}</td>
                  </tr>
                );
              })}
            </tbody>
          </Table>
          {/* <div>{JSON.stringify(user.data["data"])}</div> */}
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search