简体   繁体   中英

Component renders and gives an error before the data is completely loaded from the API

I am pulling data from a crypto coin API. It has 250 coins data in one request. But if I load all of them, the data is not loaded and component tries to render which gives an error. I am following the regular practice of await and useEffect but still the error is persistent.

const Home = () => {
  const [search, setSearch] = useContext(SearchContext);

  const [data, setData] = useState(null);

  const [loading, setLoading] = useState(true);

  const getCoinsData = async () => {
    try {
      const response = await Axios.get(
        `https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=100&page=1&sparkline=true&price_change_percentage=1h%2C24h%2C7d`
      );
      setData(response.data);
      setLoading(false);
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    getCoinsData();
  }, []);

  const negStyle = {
    color: "#D9534F",
  };
  const positiveStyle = {
    color: "#95CD41",
  };

  return (
    <div className="home">
      <div className="heading">
        <h1>Discover</h1>
        <hr className="line" />
      </div>
      {!loading || data ? (
        <div style={{ width: "100%", overflow: "auto" }}>
          <table *the entire table goes here* />
            
        </div>
      ) : (
        <img className="loading-gif" src={Loading} alt="Loading.." />
      )}
    </div>
  );
};

export default Home;

This is the entire code. Still when I try to refresh, it gives errors based on how much data loads. Sometimes, .map function is not defined or toFixed is defined etc. It does not keep loading till the whole data is loaded.

Can you show the errors and how did you initialize your state loading and data so we can debug better?

Otherwise, what I usually do in this case is:

if (!loading && data) return <Table />;
return <img className="loading-gif" ... />;
import { QueryClient, QueryClientProvider, useQuery } from "react-query";
import axios from "axios";
import React from "react";
import { Image } from "@chakra-ui/image";

const Crypto = () => {
  const { data, isLoading } = useQuery("crypto", () => {
    const endpoint =
      "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=80&page=1&sparkline=true&price_change_percentage=1h%2C24h%2C7d";
    return axios.get(endpoint).then(({ data }) => data);
  });

  return (
    <>
      {!isLoading && data ? (
        data?.map((e, id) => <Image key={id} src={e.image} />)
      ) : (
        <p>Loading</p>
      )}
    </>
  );
};

export default function App() {
  const queryClient = new QueryClient();

  return (
    <QueryClientProvider client={queryClient}>
      <Crypto />
    </QueryClientProvider>
  );
}

CodeSandBox Link, Preview

enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM