Fetching data refers to the process of making a request to a website or API and retrieving the data it returns. This is a fundamental aspect of web development, as it enables applications to interact with external services, databases, or other data sources to provide dynamic and up-to-date information to users.
The fetch() function is a built-in JavaScript function used to make network requests. It takes the URL of the API as input and returns a promise, which can be handled using the .then() method. The response is typically converted into a JavaScript object using the .json() method.
// Basic Implementation of the Fetch function
fetch("<https://catfact.ninja/fact>")
.then((res) => res.json())
.then((data) => {
console.log(data);
});
While the fetch() function is a powerful tool for making network requests, developers often prefer using libraries like Axios due to its enhanced functionality and ease of use. Here are some reasons why Axios is favored:
fetch(), you need to explicitly call the .json() method to parse the response. Axios automatically handles JSON data, reducing boilerplate code.fetch() function does not throw errors for HTTP status codes like 404 or 500. It only rejects the promise if there is a network failure. Axios, on the other hand, treats HTTP status codes outside the range of 2xx as errors, making it easier to handle such cases.When a component is rendered and mounted in a React application, it may need to fetch data from an API. If not managed properly, this can result in an infinite loop of data fetching and component updates. To prevent this, we use the useEffect() hook to ensure that the data fetch occurs only once when the component is mounted.
Hereβs an example of how to do this using Axios:
import React, { useState, useEffect } from "react";
import Axios from "axios";
export default function App() {
const [state, setState] = useState("");
useEffect(() => {
Axios.get("INSERT YOUR API URL HERE").then((res) => {
setState(res.data);
});
}, []);
return <div>{state}</div>;
}
Dynamic URLs are essential for creating flexible and adaptable web applications. By incorporating variables into API endpoints, we can adjust requests based on user input, state changes, or other conditions. This is particularly useful when the data we need to fetch depends on parameters that can change dynamically.
Letβs create an example where users can select an excuse category, and the application fetches and displays an excuse from that category using the https://excuser-three.vercel.app/v1/excuse API.
import React, { useState } from "react";
import Axios from "axios";
export default function App() {
const [excuseCategory, setExcuseCategory] = useState("family");
const [excuse, setExcuse] = useState("");
const fetchExcuse = () => {
const url = `https://excuser-three.vercel.app/v1/excuse/${excuseCategory}/`;
Axios.get(url)
.then((res) => {
// Assuming the API returns an array of excuses
setExcuse(res.data[0].excuse);
})
.catch((error) => {
console.error("Error fetching the excuse:", error);
});
};
return (
<div>
<h1>Get an Excuse</h1>
<select
value={excuseCategory}
onChange={(e) => setExcuseCategory(e.target.value)}
>
<option value="family">Family</option>
<option value="office">Office</option>
<option value="children">Children</option>
<option value="college">College</option>
<option value="party">Party</option>
</select>
<button onClick={fetchExcuse}>Get Excuse</button>
<p>{excuse}</p>
</div>
);
}