I’m using axios to pull data from an API (arr of objects) but for some reason I keep getting promise pending when calling it inside the hook.
I used promise chaining to ensure that the code executes synchronously but it’s still the same.
When I for example use "console.log(selectedVideo[0]" I get "undefined". I assume it’s because it’s calling API before it has finished pulling the data, correct?
const url = `${baseURL}videos?api_key=${apiKEY}`;
const fetchData = axios
.get(url)
.then((resp) => setSelectedVideo(resp.data));
useEffect(() => {
fetchData();
}, []);
// sets the state for the video
const [selectedVideo, setSelectedVideo] = useState(fetchData);
console.log(selectedVideo);
>Solution :
This code will be executed on each component re-render, even the fetchData result will not be a function, it will be undefined ( the return from setSelectedVideo ), you need to turn fetchData to function.
Also, as the data come from API you need to set a default value for the state for example null or an empty object
I think what you are looking for is.
const url = `${baseURL}videos?api_key=${apiKEY}`;
const fetchData = () => axios
.get(url)
.then((resp) => setSelectedVideo(resp.data));
useEffect(() => {
fetchData();
}, []);
const [selectedVideo, setSelectedVideo] = useState(null);