Fetching Data From API With useState and useEffect Hooks In React App

In previous blog post, we learned how to get started with creating a very basic react app. In this blog post we will share a snippet to fetch data from API route with useState and useEfeect hooks in react app. Following is the snippet code:

import {useState, useEffect} from 'react';
const [data, setData] = useState([]);
useEffect(() => {
    const fetchData = async() => {
      const result = await fetch("api_url_here").then(
        response => response.json()
      );
      setData(result);
    }
    fetchData();
}, []);
{
       data.map(project => (
        <div key={project.id}>
          <h2>{project.title}</h2>
          <p>{project.content}</p>
        </div>
       ))
}

Leave a Comment