score:8

Accepted answer
import react, { usememo, usestate, useeffect } from "react";
import axios from "axios";
import table from "./table";
import "./app.css";

function app() {
  // here you set a state to tell the component it need to wait
  //  until the result is fetched from the api
  const [loadingdata, setloadingdata] = usestate(true);
  const columns = usememo(() => [
    {
      header: "state",
      accessor: "state",
    },
    {
      header: "positive cases",
      accessor: "positive",
    },
    {
      header: "recovered cases",
      accessor: "recovered",
    },
  ]);

  const [data, setdata] = usestate([]);

  useeffect(() => {
    async function getdata() {
      await axios
        .get("https://covidtracking.com/api/v1/states/current.json")
        .then((response) => {
          // check if the data is populated
          console.log(response.data);
          setdata(response.data);
          // you tell it that you had the result
          setloadingdata(false);
        });
    }
    if (loadingdata) {
      // if the result is not ready so you make the axios call
      getdata();
    }
  }, []);

  return (
    <div classname="app">
      {/* here you check if the state is loading otherwise if you wioll not call that you will get a blank page because the data is an empty array at the moment of mounting */}
      {loadingdata ? (
        <p>loading please wait...</p>
      ) : (
        <table columns={columns} data={data} />
      )}
    </div>
  );
}

export default app;

example of the result

object


Related Query

More Query from same tag