Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with fetching data

iam new to React and trying to show data from API,
It works at first but after reload i got error " Cannot read properties of undefined (reading ‘length’)",
any ideas what could it cause ?
thanks

code looks like this:

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

const options = {
//options for API call
};

const Ticket = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch(
      "https://daily-betting-tips.p.rapidapi.com/daily-betting-tip-api/items/daily_betting_coupons?sort=-id",
      options
    )
      .then((res) => res.json())
      .then((data) => {
        setData(data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <p>data is loading...</p>;
  }

  return (
    <div>
      <h1>length: {data.data.length}</h1>
      
      <h2></h2>
    </div>
  );
};

export default Ticket;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use this code. I edited your code. Add a condition when set your data variable

if(data.data) {
  setData(data.data)
}

And also change this line

<h1>length: {data.data.length}</h1>

To

<h1>length: {data.length}</h1>

Here is the full code

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

const options = {
  //options for API call
};

const Ticket = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch(
      "https://daily-betting-tips.p.rapidapi.com/daily-betting-tip-api/items/daily_betting_coupons?sort=-id",
      options
    )
      .then((res) => res.json())
      .then((data) => {
        if (data.data) {
          setData(data.data);
        }
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <p>data is loading...</p>;
  }

  return (
    <div>
      <h1>length: {data.length}</h1>

      <h2>Hello world</h2>
    </div>
  );
};

export default Ticket;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading