ReactJS is a popular JavaScript library used for building user interfaces. It allows developers to create reusable components that can be easily composed to build complex UIs. In this blog post, we'll be exploring how to fetch data from a dummy API in ReactJS using the fetch() function.
First, we need to create a dummy API that we can use to fetch data. We can use a service like jsonplaceholder.typicode.com to create a simple API that returns JSON data.
{
"id": 1,
"title": "sunt aut facere repellat provident",
"body": "quia et suscipit\nsuscipit... ",
"userId": 1
}
Next, we'll create a new React component called Posts. We'll use the useState hook to create a state variable called posts that will hold the data returned from the API.
import React, { useState, useEffect } from "react";
function Posts() {
const [posts, setPosts] = useState([]);
// ...
}
We're also importing the useState and useEffect hooks and the React library at the top of our file. We'll use the useEffect hook to fetch the data from the API when the component is mounted.
function Posts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => setPosts(data));
}, []);
// ...
}
In the useEffect hook, we're using the fetch() function to make a GET request to the API endpoint. We're then using the then() method to convert the response to JSON and set the posts state variable to the returned data. We also pass an empty array [] as the second argument to the useEffect hook, which ensures that the effect only runs once when the component is mounted. Finally, we'll render the data returned from the API using JSX syntax.
function Posts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => setPosts(data));
}, []);
return (
<div>
<h1>Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
}
In the return statement, we're using JSX syntax to render the title and body of each post in the posts state variable. We're also using the map() method to loop through the posts array and create a list item for each post. To use this component in another file, we simply need to import it and render it like this:
import React from "react";
import Posts from "./Posts";
function App() {
return (
<div>
<Posts />
</div>
);
}
export default App;
This will render the Posts component and display the data returned from the API.
In conclusion, fetching data from a dummy API in ReactJS is a great way to learn how to use the `fetch.