How to fetch data from a remote API in React.js

In this post, I will show you fetching data from a remote source inside your React.js application. So let’s create a brand new React project with 

fetch data from a remote API

Initialize a React project

If you succeed in executing the above commands, you will see the default React page in the browser at http://localhost:3000.

Now Let’s get into the fetching remote data task, for the sake of simplicity, in this article, we will use the native fetch API that comes with the browser. It uses JavaScript promises to resolve the asynchronous response. 

Let’s create a brand new component called Todo, for this create a file called Todo.js with following code in the src directory.

Our todo component is ready to import, let’s import it into the App component, for the sake of simplicity I have removed all the default code from the App component render method, and the final version will be like below shown:

And if you see the output of this state by visiting http://localhost:3000, it will show the Todos List text in the browser.

Now let’s define constructor() method and assign the initial state as shown below

Now update the render method as shown below,

In the preceding code in the renderTodos(), we are iterating over the todos and pushing items into the todosList array.

Now let’s fetch the content from the remote API, for this componentDidMount() lifecycle method is the best place. So let’s define it:

In preceding code, we are calling the setState() method in the response of fetch API callback. and this will update the state of the component(todos) and it will trigger an extra rendering but it will happen before the browser updates the screen.  This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. 

Now if you visit http://localhost:3000, you will the todos list in the browser.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status