Home > Mobile >  Issue with fetching data
Issue with fetching data

Time:10-03

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;

CodePudding user response:

You are getting this error because you have data state which is an array but in return you are trying to access data key from the state's data array, which is not there hence it returns the undefined and then you are trying to access the length from undefined.

Instead of data.data.length just use data.length

CodePudding user response:

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;
  • Related