Lesson 11 - Web Service Calls In React

11.2 - Using Fetch

The fetch API is a modern, built-in JavaScript function that allows you to make HTTP requests to interact with APIs. It's widely used in React for making web service calls.

This chapter will cover basic fetch operations with examples. Let's get started.

Retrieving Data: The HTTP GET method is used to retrieve data from a database or other resources. It's commonly used to request and fetch information from a server. Below is an example of how to retrieve data using the GET method:

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

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

 useEffect(() => {
 fetch('https://jsonplaceholder.typicode.com/posts')
 .then(response => response.json())
 .then(data => {
 setData(data);
 })
 .catch(error => console.error('Error fetching data:', error));
 }, []);

  
 return (
 <ul>
 {data.map(post => (
 <li key={post.id}>{post.title}</li>
 ))}
 </ul>
 );
}

Here, the useEffect hook extracts data using fetch and updates the data state using the setData() method. Lastly, it maps the JSON data using the map() function.

POST Data: The HTTP POST method is the most secure way to transfer data since the information in a request is encrypted. That's why it's mainly used in events like form submission, login, sign-up, etc.

The following example demonstrates how to transmit data using a POST request. In this example, we'll send data to a server.

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

function App() {
 const [title, setTitle] = useState('');
 const [body, setBody] = useState('');
 const [response, setResponse] = useState(null);

 const handleSubmit = (event) => {
 event.preventDefault();

 fetch('https://jsonplaceholder.typicode.com/posts', {
 method: 'POST',
 headers: {
 'Content-Type': 'application/json',
 },
 body: JSON.stringify({
 title: title,
 body: body,
 userId: 1,
 }),
 })
 .then(response => response.json())
 .then(data => {
 setResponse(data);
 })
 .catch(error => console.error('Error posting data:', error));
 };

 return (
 <div>
 <form onSubmit={handleSubmit}>
 <label>
 Title:
 <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
 </label>
 <br />
 <label>
 Body:
 <textarea value={body} onChange={(e) => setBody(e.target.value)} />
 </label>
 <br />
 <button type="submit">Submit</button>
 </form>
 {response && (
 <div>
 <h2>Response</h2>
 <pre>{JSON.stringify(response, null, 2)}</pre>
 </div>
 )}
 </div>
 );
}

The handleSubmit function prevents the default form submission and uses fetch to send a POST request to the API. The method defines the request method we're using. In this case, it's the POST method. The Content-Type properties inside the header define the receiving data type which is JSON for our example. The response from the API is stored in the response state and displayed to the user.

DELETE Post: To delete data from an API, you can use the DELETE method. This is particularly useful for tasks such as removing specific users from a database.

Have a look at the following example:

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

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

 useEffect(() => {
 fetch('https://jsonplaceholder.typicode.com/posts')
 .then(response => response.json())
 .then(data => {
 setData(data);
 })
 .catch(error => console.error('Error fetching data:', error));
 }, []);

 const handleDelete = (id) => {
 fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
 method: 'DELETE',
 })
 .then(() => {
 setData(data.filter(post => post.id !== id));
 })
 .catch(error => console.error('Error deleting data:', error));
 };

 return (
 <ul>
 {data.map(post => (
 <li key={post.id}>
 {post.title} <button onClick={() => handleDelete(post.id)}>Delete</button>
 </li>
 ))}
 </ul>
 );
}

First, we fetch the data through an API call then we define a handler function handleDelete. The handleDelete function sends a DELETE request to the API and removes the deleted item from the state. Like our previous example, the method defines the request method we're using. In this case, it's the DELETE method.