I'm getting the following warning in the console:
Line 19:6: React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array
and res.data
is an empty array when I console log it.
But when I pass in data
to the dependency array, I do get the correct API response in the console, but I get an infinite loop.
From what I've read, this is one of the most common traps to fall into when using useEffect, but I still have a hard time wrapping my head around how to resolve this or finding an answer I can truly understand.
Any help would be appreciated in what is currently wrong with my code, and how to resolve.
import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
const apiKey = process.env.REACT_APP_NASA_KEY;
const NasaPhoto = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const res = await axios(
`https://api.nasa.gov/planetary/apod?api_key=${apiKey}`
);
setData(res.data);
console.log(data);
};
fetchData();
}, []);
return (
<div>
<Link to='/'>Return Home</Link>
<h1>Nasa Data</h1>
</div>
);
};
export default NasaPhoto;