What Does Fetching Data Mean? 🌐

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.

Basic Fetch Implementation πŸ› οΈ

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);
	});

Why is Axios Preferred Over Fetch? πŸ€”

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:

  1. Simplicity and Readability: Axios simplifies the process of making requests and handling responses, resulting in cleaner and more readable code.
  2. Automatic JSON Data Handling: With fetch(), you need to explicitly call the .json() method to parse the response. Axios automatically handles JSON data, reducing boilerplate code.
  3. Error Handling: The 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.
  4. Request and Response Interceptors: Axios allows you to intercept requests or responses before they are handled, enabling modifications to requests, addition of headers, or centralized error handling.

Handling Infinite Data Calls via API πŸ”„

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>;
}

Using Dynamic URLs in API Requests 🌍

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.

Example: Fetching Excuses from an API 🎭

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>
  );
}