Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get data from api in ReactJS

Understanding APIs

APIs, or Application Programming Interfaces, are like the waitstaff at your favorite restaurant. You, the customer, ask for something (like a plate of pasta), and the waiter goes to the kitchen to get it for you. In this analogy, the kitchen is the server where data is stored, and the waiter is the API that retrieves the data for you. This is what happens when your application interacts with an API: it sends a request for data, and the API retrieves it.

What is Fetching Data?

"Fetching data" is a way to ask for and receive data from an API. It is like if you were playing a game of fetch with your dog: you throw the Frisbee (the request), and your dog runs to grab it and bring it back (the data).

Fetching Data in ReactJS: An Overview

ReactJS, a popular JavaScript library for building user interfaces, doesn't contain built-in functions to fetch data. Instead, it relies on JavaScript's Fetch API or other libraries like axios. We'll focus on the Fetch API in this blog post.

Using JavaScript's Fetch API

Before we dive into how to use it in a React component, let's briefly understand how Fetch API works:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

In the above code, we're sending a request to the URL https://api.example.com/data. The fetch() function returns a Promise that resolves to the Response object representing the response of the request. This Response object is then converted to JSON using the json() method. Finally, we're logging the data to the console.

Fetching Data in a React Component

Now, let's see how we can integrate this into a React component. We'll create a simple component that fetches data from an API and displays it.

class DataFetcher extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
      isLoading: false,
      error: null,
    };
  }

  componentDidMount() {
    this.setState({ isLoading: true });
    fetch('https://api.example.com/data')
      .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('Something went wrong ...');
        }
      })
      .then(data => this.setState({ data, isLoading: false }))
      .catch(error => this.setState({ error, isLoading: false }));
  }

  render() {
    const { data, isLoading, error } = this.state;
    if (error) {
      return <p>{error.message}</p>;
    }
    if (isLoading) {
      return <p>Loading ...</p>;
    }
    return (
      <div>
        {data.map(item => (
          <p key={item.id}>{item.title}</p>
        ))}
      </div>
    );
  }
}

Understanding the React Component

Let's break down what's happening in this component:

In the constructor(), we initialize the state with data (to store the fetched data), isLoading (to indicate whether the data is still being fetched), and error (to store any error that occurred during fetching).

In the componentDidMount() lifecycle method, we start the data fetching process. We set isLoading to true, then we use the fetch() function to send a request to the API. If the response is okay, we convert it to JSON. If not, we throw an error.

After getting the JSON data, we update the state with the fetched data and set isLoading to false.

If there's an error during the process, we catch it and update the state with the error message and set isLoading to false.

In the render() method, we first check if there's any error. If so, we render the error message. If the data is still loading, we display a loading message. Finally, if we have the data, we map over it and display it.

Conclusion

Fetching data from an API and displaying it is a common task in modern web development. With ReactJS and the Fetch API, we can handle this task with ease. In this blog post, we've seen how a React component can fetch data from an API, handle loading states, and catch and display errors.

Remember, APIs are like our helpful waiters, and fetching data is like playing a fun game of fetch with them. Keep practicing, and soon, you'll be able to fetch data like a pro with your furry friend (or in our case, with your React applications). Happy coding!