DEV Community

ahmad
ahmad

Posted on

Can anyone guide me in a simple question in React.js?

I am fetching an API and assigning its data to an object by using setArticles. Problem is, I am mapping on "articles.map()" this data in Functional component and get an error, because state articles have null value before fetching data. Please see screenshot attached if I am not making sense, sorry for that.

Issue is, component gets rendered first, and at that render time, "articles" have no value, and I am assigning it a value after fetching.
Question is

  1. How can I fetch data and use it in a component? Image description

Top comments (3)

Collapse
 
9hnd5 profile image
9hnd5

There several things we need to discuss here

  1. It is recommended to always fetch data from an effect rather than directly in a component.
  2. It is advisable to format your code for better readability. Properly formatted code enhances code comprehension and makes it easier for others to collaborate on the project

The correct version maybe look like:

export default function News(){
      const [articles, setArticles] = React.useState([]);

      articles.map(data => console.log(data));

      React.useEffect(async () => {
            const result = await fetch(...);
            const articles = result.json();
            setArticles(articles);
      }, ['your dependencies'])
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ahmadarif0921 profile image
ahmad

OMG
I finally achieved it.
Here is a screenshot attached with right way.
Image description

Collapse
 
ahmadarif0921 profile image
ahmad

Thanks for your reply
Unfortunately, nothing helped.
you declared a const "articles" 2 times.
Once in state, second, after fetch...