Ryan Speciale
Ryan Speciale

Reputation: 178

Infinite Loop caused when trying to fetch data and render it with React

I'm having a problem fetching data and rendering it with React. It works fine when I am hitting an API that returns a single object but when I query a news API it just continues to run in an infinite loop even when I limit the amount of articles I want to return. I am saving the return data with useState and fetching it with useEffect. What am I doing wrong? Here is my code.

  const classes = useStyles();
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const getData = async () => {
      const url = 'https://gnews.io/api/v4/search?q=malware&lang=en&max=3&token=MY_API_TOKEN'
      const res = await fetch(url);
      const data = res.json();
      console.log(data);
      setData(data);
      setLoading(false);
    };
    getData();
  })
  
  
  return (
      <div className={classes.root}>
        <Grid 
        container
        direction="row"
        justifycontent="center"
        alignItems="center"
        spacing={8}
        >
          <Grid item xs={12}>
            <Paper className={classes.paper1}>
              <Typography variant="h5" className={classes.title}>
              "This book is dedicated to anyone and everyone who understands that
hacking and learning is a way to live your life, not a day job or 
semi-ordered list of instructions found in a thick book." -The Shellcoder's Handbook
              </Typography>
            </Paper>
          </Grid>
          <Grid container spacing={2}>
           <Grid item xs={4}>
           <Paper className={classes.paper2}>
              <h1>Title of news article</h1>
                <p>news story explination</p>
                <p>image</p>

            </Paper>
           </Grid>
           <Grid item xs={4}>
           <Paper className={classes.paper2}>
              <h1>Title of news article</h1>
                <p>news story explination</p>
                <p>image</p>

            </Paper>
           </Grid>
           <Grid item xs={4}>
           <Paper className={classes.paper2}>
              <h1>{data.title}</h1>
                <p>news story explination</p>
                <p>image</p>

            </Paper>
           </Grid>
          </Grid>
        </Grid>
      </div>
  )
};```

Upvotes: 0

Views: 1629

Answers (1)

Viet
Viet

Reputation: 12817

You need to add dependencies in your useEffect. If you want only call getData one time, you can add empty dependency [] like this

  useEffect(() => {
    const getData = async () => {
      const url = 'https://gnews.io/api/v4/search?q=malware&lang=en&max=3&token=MY_API_TOKEN'
      const res = await fetch(url);
      const data = res.json();
      console.log(data);
      setData(data);
      setLoading(false);
    };
    getData();
  }, [])

Upvotes: 2

Related Questions