Skip to content

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

Last updated on June 6, 2022

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 npx.

Initialize a React project

$ npx create-react-app todos
$ cd todos
$ npm start

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 the following code in the src directory.

import React, { Component } from 'react';

class Todo extends Component {

    render() {
        return (

Todos List

        );
    }
}

export default Todo;

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 the below shown:

import React, { Component } from 'react';
import './App.css';
import Todo from './todo/Todo'

class App extends Component {
  render() {
    return (
    );
  }
}
export default App;

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 the constructor() method and assign the initial state as shown below

constructor(props) {
    super(props)
    this.state = {
       todos: []
   }
}

Now update the render method as shown below,

    renderTodos() {
        let todoList = []
        this.state.todos.map(todo => {
            return todoList.push(
  • {todo.title}
)
        })

        return todoList;
    }

    render() {
        return (

Todos List

    {this.renderTodos()}
        );
    }

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:

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/todos')
            .then(response => response.json())
            .then(todos => {
                this.setState({
                    todos: todos.data
                })
            })
            .catch(error => console.log(error))
    }

In the 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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments