Home > OS >  Having difficulty retrieving data from useEffect hook in React
Having difficulty retrieving data from useEffect hook in React

Time:08-05

I'm having some trouble with my useEffect hook that I just cannot seem to get it to work. I'm trying to make a call to this endpoint, however, I believe that I am getting nothing back.

I would really appreciate any help.(I've updated my X-RapidAPI-Key, so that it does not display here of course). My 'console.log(json)' appears to retrieve no results, so I'm at a bit of a loss.

I'm trying to follow the guidelines as per the website's advice here https://rapidapi.com/api-sports/api/api-football/

My code is as follows

import React, { useState, useEffect } from "react";  // Changed
import Header from "../components/headerTeamList";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import TeamList from "../components/teamList";

const useStyles = makeStyles({
  root: {
    padding: "20px",
  },
});

const TeamListPage = (props) => {
  const classes = useStyles();
  const [teams, setTeams] = useState([]);
  console.log(teams)

  useEffect(() => {
    const options = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': '**********************',
        'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com'
      }
    };

    fetch('https://api-football-v1.p.rapidapi.com/v3/standings/?season=2021&league=39', options)
      .then((res) => res.json())
      .then((json) => {
        console.log(json);
        return json.response;
      })
      .then((teams) => {
        setTeams(teams);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Grid container className={classes.root}>
      <Grid item xs={12}>
        <Header title={"Home Page"} />
      </Grid>
      <Grid item container spacing={5}>
        <TeamList teams={teams}></TeamList>
      </Grid>
    </Grid>
  );
};
export default TeamListPage;

CodePudding user response:

One thing that's (at least) not helping you right now is that you don't have a .catch block, you can console.log(response) all day but if an error is occur and you don't console.log(error), you won't know what went wrong and why. (that is if you are like me and debugging by console loggin lol)

Try this. at least it would tell you why its not working.

  fetch('https://api-football-v1.p.rapidapi.com/v3/standings/?season=2021&league=39', options)
    .then((res) => res.json())
    .then((json) => {
      console.log(json);
      return json.response;
    })
    .then((teams) => {
      setTeams(teams);
    })
    .catch(error => console.log(error));
// eslint-disable-next-line react-hooks/exhaustive-deps

If you want to do async.. await

useEffect(() => {
  const fetchFunction = async (url, opt) => {
    try {
      const reponse = await fetch(url, opt);
      const responseJson = await response.json();
      const data = await responseJson.response;
      setTeam(data);
    } catch (error) {
      console.log(error);
    };
  };
  // remember to actually call it 
  fetchFunction('https://api-football-v1.p.rapidapi.com/v3/standings/?season=2021&league=39', options)
}, []);

Reminder that you cannot do async.. await on the top level with useEffect, hence why we gotta define a function and call it, it's silly, but it is what it is.

CodePudding user response:

You are probably getting lost inside in one of the multiple .then. Why don't you try something like this:

const OPTIONS = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': '**********************',
        'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com'
      }
    };

const handleFetch = async () => {
 const response = await fetch('https://api-football-v1.p.rapidapi.com/v3/standings/?season=2021&league=39', options);
const json = await response.json();

setTeams(json);

}

useEffect(() => {
 handleFetch();
}, [])
  • Related