πŸ‘ŒHandle API Professionally

Tutorial Resources πŸ‘

🧐 Server-Side Code

const express = require("express");

const app = express();

app.get("/api/products", (req, res) => {
  const products = [
    {
      id: 1,
      name: "camera",
      price: 20000,
      image:
        "https://dfstudio-d420.kxcdn.com/wordpress/wp-content/uploads/2019/06/digital_camera_photo-1080x675.jpg",
    },
    {
      id: 2,
      name: "table glass",
      price: 3000,
      image: "https://m.media-amazon.com/images/I/81X4SfkV9JL._AC_SL1500_.jpg",
    },
  ];

  if (req.query.search) {
    // reading all products information and storing in filterProducts
    const filterProducts = products.filter((product) =>
      product.name.includes(req.query.search)
    );
    // Sending all products information
    res.send(filterProducts);
    return; // stop processing
  }
  // sending data to client after 3s
  setTimeout(() => {
    res.send(products);
  }, 3000);
});


const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

😲 Client-Side Code: API handling using Axios

import "./App.css";
import axios from "axios";
import { useEffect, useState } from "react";

function App() {
  // To store products details
  const [products, setProducts] = useState([]);

  // To Check if errors occured or not while fetching products
  const [error, setError] = useState(false);

  // wait untill all products are fetched : a simple loading function
  const [loading, setLoading] = useState(false);

  // Fetches all products as soon website startts
  useEffect(() => {
    // wait untill all products are fetched using async
    (async () => {
      // handling errors condition if error occurs in fetching products
      try {
        setLoading(true); // loading starts
        setError(false); // no response errors

        // making a api call to fetch all products
        // which will be fetched in response variable
        const response = await axios.get("/api/products");
        console.log(response.data);

        // storing all products in products
        setProducts(response.data);
        setLoading(false); // stop loading animation
      } catch (error) {
        setError(true); // error handling showing error message
        setLoading(false); // stop loading animation
      }
    })();
  }, []);

  // Shows error message when fetching failed data
  if (error) {
    return <h1> Something went wrong </h1>;
  }
  // Create a loading animation when fetching the data
  if (loading) {
    return <h1> loading...</h1>;
  }
  return (
    <>
      <h1> Chai aur API in react </h1>
      {/* {loading && <h1>Loading............</h1>} */}
      <h2> Number of Products are: {products.length}</h2>
    </>
  );
}
export default App;

Last updated