0

I was trying to fetch API with react.js but on first render its gives nothing and the second render its gives data. This makes it so when I try to access the data later for an image I get an error:

TypeError: Cannot read property 'news.article' of undefined, because it is initially empty.

How can I solve this?

photo

Here is my code ..

import React, { useEffect, useState } from 'react';

const HomeContent = () => {
    const [news, updateNews] = useState([]);
    console.log(news);
    useEffect(() => {
        const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
        fetch(api)
            .then(response => response.json())
            .then(data => updateNews(data))
            .catch((error) => console.log(error))
    }, [])

    return (
        <>

        </>
    );
};

export default HomeContent;
7
  • You don't need to "solve" it. That's how it is supposed to work. Commented Feb 26, 2021 at 16:44
  • This makes it so when I try to access the data later for an image I get an error, TypeError: Cannot read property 'news.articles' of undefined, because it is initially empty. Commented Feb 26, 2021 at 16:47
  • Re edit: At no point in the code you've shared with us do you try to read any property of news (let alone news.articles so that code can't produce that error. (And if news is going to get a property called articles then it doesn't make sense to initialize it to an empty array). Commented Feb 26, 2021 at 16:47
  • Usually you would have an additional loading state, that you set to false when the request finished. You can then render some kind of loading indicator, while loading is still true. For a more sophisticated app you will also need some state to handle errors while fetching the data. Commented Feb 26, 2021 at 16:53
  • Can I have an example of code? @trixn Commented Feb 26, 2021 at 16:55

1 Answer 1

1

There is no issue with the code itself, the output you receive is expected. However, you can render the content after it is retrieved as such

import React, { useEffect, useState } from 'react';

const HomeContent = () => {
    const [news, updateNews] = useState([]);
    const [isLoading, setIsLoading] = useState(true);    

    console.log(news);
    useEffect(() => {
        const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
        fetch(api)
            .then(response => response.json())
            .then(data => { 
                updateNews(data.articles);
                setIsLoading(false);
            })
            .catch((error) => {
               console.log(error);
               setIsLoading(false);
            })
    }, [])

    return (
        <>
            {isLoading ? 
                <p>Loading...</p> :
                // Some JSX rendering the data
            }
        </>
    );
};

export default HomeContent;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.