Skip to Content
šŸ‘† We offer 1-on-1 classes as well check now
React.jsAPI IntegrationFetch API

Fetch API

The Fetch API is a modern, promise-based interface for making HTTP requests in React applications. It provides a simple and efficient way to interact with web servers, allowing you to fetch data, send data, and perform other HTTP operations. With React 19, you can leverage the Fetch API to build robust and scalable applications.

Basic Example

To get started with the Fetch API, you can use the fetch() function to make a simple GET request. Here’s an example:

import React, { useState, useEffect } from 'react'; function FetchExample() { const [data, setData] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => setData(data)); }, []); return ( <div> {data ? ( <ul> {data.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> ) : ( <p>Loading...</p> )} </div> ); } export default FetchExample;

In this example, we use the fetch() function to make a GET request to the JSONPlaceholder API, which returns a list of posts. We then use the useState() hook to store the response data and the useEffect() hook to fetch the data when the component mounts.

Advanced Usage

You can also use the Fetch API to make POST requests, send headers, and handle errors. Here’s an example of how to make a POST request:

import React, { useState } from 'react'; function PostExample() { const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const handleSubmit = (event) => { event.preventDefault(); fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title, body, }), }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); }; return ( <form onSubmit={handleSubmit}> <label> Title: <input type="text" value={title} onChange={(event) => setTitle(event.target.value)} /> </label> <label> Body: <textarea value={body} onChange={(event) => setBody(event.target.value)} /> </label> <button type="submit">Submit</button> </form> ); } export default PostExample;

In this example, we use the fetch() function to make a POST request to the JSONPlaceholder API, sending a JSON payload with the title and body of the post.

Best Practices

When using the Fetch API in your React applications, keep the following best practices in mind:

  • Always handle errors using the catch() method to prevent your application from crashing.
  • Use the then() method to handle successful responses and parse the response data.
  • Set the correct Content-Type header when sending data in the request body.
  • Use the useEffect() hook to fetch data when the component mounts, and avoid fetching data in the render method.

Key Takeaways

  • The Fetch API is a modern, promise-based interface for making HTTP requests in React applications.
  • Use the fetch() function to make GET, POST, PUT, and DELETE requests.
  • Always handle errors using the catch() method and set the correct Content-Type header when sending data.
  • Use the useEffect() hook to fetch data when the component mounts, and avoid fetching data in the render method.
Last updated on