'In Reactjs how to insert api data into ant design table

I am new to Reactjs currently I'm working on antdesign table I want to fetch a data from external API and insert data into table but it give me error I also also google it but nothing found please help me below is my code

import React, { useState, useEffect } from "react";
import Axios from "axios";
import { Table } from "antd";

function App() {
  const [state, setstate] = useState({});
  const [loading, setloading] = useState(true);
  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    const res = await Axios.get(
      "https://jsonplaceholder.typicode.com/comments"
    );

    setstate(res.data);
    setloading(false);
  };
  const data = loading
    ? "wait"
    : state.map(row => ({ Name: row.name, Email: row.email }));

  const columns = [
    {
      title: "Name",
      dataIndex: "Name",
      width: 150
    },
    {
      title: "Email",
      dataIndex: "Email",
      width: 150
    }
  ];

  return (
    <div>
      <Table
        columns={columns}
        dataSource={data}
        pagination={{ pageSize: 50 }}
        scroll={{ y: 240 }}
      />
      ,
    </div>
  );
}

export default App;

And here is codesandbox.io



Solution 1:[1]

in addition to the accepted answer, note in the following snippet the conditional rendering also how to use state, setState functions,I suggest to check the documentation on how to use react hooks:

here is a better implementation of your code:

import React, { useState, useEffect } from "react";
import Axios from "axios";
import { Table } from "antd";

function App() {
  const [state, setstate] = useState([]);
  const [loading, setloading] = useState(true);
  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    await Axios.get("https://jsonplaceholder.typicode.com/comments").then(
      res => {
        setloading(false);
        setstate(
          res.data.map(row => ({
            Name: row.name,
            Email: row.email,
            id: row.id
          }))
        );
      }
    );
  };

  const columns = [
    {
      title: "Name",
      dataIndex: "Name",
      width: 150
    },
    {
      title: "Email",
      dataIndex: "Email",
      width: 150
    }
  ];

  return (
    <div>
      {loading ? (
        "Loading"
      ) : (
        <Table
          columns={columns}
          dataSource={state}
          pagination={{ pageSize: 50 }}
          scroll={{ y: 240 }}
        />
      )}
    </div>
  );
}

export default App;

codesandbox

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ROOT