Fetching Data From API In React-Native

Paddy
3 min readJan 11, 2019

Each Idea is worthless and meaningless if we don’t work on it, thats what also happened with me, i wrote that idea on paper like in first week of November and after that i didn’t work on it. Until start of December, My App was based on the latest news, and my main roadblock was, where can I find a good API with features which will have good amount of news to fetch, to display in my app and that to free. I researched a lot for good API on internet, after some time I realise that I was searching in wrong section, when I typed for News API on google search the first link was my solution. I came to know about this site called News API , they were sharing the latest news, with many features like, serval categories, news from various country, also news from various news paper. So that’s it, I got the API I needed now it was time to fetch it and display in list form on the app.

I used ListView from React-Native to display news. It is very simple process, you need to run the api link and the result you need to store in a state. Then to display in ListView just fetch data from the state variable you have just saved the data.

It is very necessay to understand the React-Native Component Lifecycle. I put a default category like general with country United State in API like this ‘https://newsapi.org/v2/top-headlines?category='genral'&country=us&apiKey=xxxxxxxx ‘, and put the code in componentDidMount so that as soon as my component gets reload my code will run and will store data in state ‘dataSource’.

Now to display the data stored in ‘dataSource’ state, I access the state and put it in parameter of ListView by name ‘dataSource’ so that now whenever there isndata inside the state ‘dataSource’ you will get a list of row with the data.

When my url https://newsapi.org/v2/top-headlines?country=us&apiKey=xxxxxxxx runs it will give me data in JSON format, you can get any JSON parser tool online to check the structure of data. Like here the structure of data is like following. All my news are stored in array called by name ‘articles’.

In above code renderSeparator is used to add a line separator between each row of the list.To access data from the dataSource state, let say I want to access News Heading then I have used ‘rowData.title’ here the ’title’ parameter is given to us by API, lets say I want to access Image of the news then I will used ‘rowData.urlToImage’, thats it.

This is how I Fetched data from the NewsApi’s API and showed in my ListView, In next blog I’ll write about how to use modal to display the total detailed view of my news, like a enlarge Image, more description, buttons like share news, bookmark, source link button. Peace.

--

--

Paddy

A React Native developer who likes paint and make videos.