Back to Course

Learn React

0% Complete
0/0 Steps
Lesson 22 of 32
In Progress

Updating State with API Data

React is a powerful library for building user interfaces, and one of its key features is the ability to manage state. In this article, we’ll look at how to update the state of a React component using data fetched from an API.

Fetching Data in a React Component

The first step in updating state with API data is to fetch the data from the API. There are a few different ways to do this, but the most common method is to use the fetch function. Here’s an example of how to fetch data in a React component:

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/endpoint')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      {data ? data.map(item => <div key={item.id}>{item.name}</div>) : 'Loading...'}
    </div>
  );
}

In this example, we use the useState hook to create a data state variable and a setData function to update the state. We then use the useEffect hook to perform the data fetch when the component mounts. The useEffect hook takes a function as an argument and will run that function after the component renders.

Updating State with Fetch Data

Once we have the data from the API, we can use it to update the state of the component. To do this, we simply call the setData function and pass it the data from the API.

fetch('https://api.example.com/endpoint')
  .then(response => response.json())
  .then(data => setData(data));

This will update the data state variable with the data from the API, and the component will re-render to display the updated data.

Conclusion

In this article, we looked at how to update the state of a React component using data fetched from an API. By using the fetch function and the useState and useEffect hooks, we can easily retrieve and display data from an API in our React application.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Write a function that fetches data from the “https://api.example.com/endpoint” API and displays it in a list on the page.

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/endpoint')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      {data ? data.map(item => <div key={item.id}>{item.name}</div>) : 'Loading...'}
    </div>
  );
}

Write a function that fetches data from the “https://api.example.com/endpoint” API and displays it in a table on the page.

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/endpoint')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        {data ? data.map(item => (
          <tr key={item.id}>
            <td>{item.id}</td>
            <td>{item.name}</td>
            <td>{item.email}</td>
          </tr>
        )) : 'Loading...'}
      </tbody>
    </table>
  );
}

Write a function that fetches data from the “https://api.example.com/endpoint” API and displays it in a dropdown menu on the page.

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/endpoint')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <select>
      {data ? data.map(item => <option key={item.id} value={item.id}>{item.name}</option>) : 'Loading...'}
    </select>
  );
}

Write a function that takes in a user’s first name and last name and returns a string that displays their full name. The function should handle any cases where the first name or last name is not provided.

function getFullName(firstName, lastName) {
  if (!firstName) {
    return lastName;
  }
  if (!lastName) {
    return firstName;
  }
  return `${firstName} ${lastName}`;
}

console.log(getFullName('John', 'Doe')); // Output: 'John Doe'
console.log(getFullName('John')); // Output: 'John'
console.log(getFullName(null, 'Doe')); // Output: 'Doe'

Write a function that takes in an array of numbers and returns the average of all the numbers. The function should handle cases where the array is empty or contains non-numeric elements.

function getAverage(numbers) {
  if (!numbers || numbers.length === 0) {
    return 0;
  }
  let sum = 0;
  let count = 0;
  for (let i = 0; i < numbers.length; i++) {
    if (typeof numbers[i] === 'number') {
      sum += numbers[i];
      count++;
    }
  }
  return sum / count;
}

console.log(getAverage([1, 2, 3])); // Output: 2
console.log(getAverage([])); // Output: 0
console.log(getAverage([1, 'a', 3])); // Output: 2