Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Promise pending when calling a function inside a hook using React

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading