Fake Store -API-Fetching -Mapping-in-React js

 To map data from the Fake Store API in a React application, follow these steps to fetch data and display it using .map().

Step-by-Step Guide

1. Set Up a React Project
If you don’t have a React project set up, create one with:
npx create-react-app fake-store-app

Navigate to the project directory: cd fake-store-app

2. Fetch Data from Fake Store API

The
Fake Store API endpoint (https://fakestoreapi.com/products) provides mock product data in JSON format. You can fetch the data in a component, such as App.js or a separate component.

3. Create the Component to Fetch and Display Data

In App.js, add the following:
import React, { useEffect, useState } from 'react';


const App = () => {
  const [products, setProducts] = useState([]);

  // Fetch data from the Fake Store API
  useEffect(() => {
    fetch('https://fakestoreapi.com/products')
      .then(response => response.json())
      .then(data => setProducts(data))
      .catch(error => console.error("Error fetching data:", error));
  }, []);

  return (
    <div className="App">
      <h1>Fake Store Products</h1>
      <div className="product-list">
        {products.map(product => (
          <div key={product.id} className="product">
            <img             src={product.image}             alt={product.title}             style={{               width: '100px'              }}              />
            <h2>{product.title}</h2>
            <p>Price: ${product.price}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;

Explanation of Code

  • State and useEffect:

    • We define products using the useState hook to store the fetched data.
    • Inside useEffect, the API call is made, and the response is saved in products.
  • Mapping the Data:

    • We use .map() on the products array to render each product.
    • Each product item includes an image, title, and price.

4. Run the Project

To view your app in the browser, run:

Styling (Optional)

You can add some CSS to style the product list:

.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.product {
  border: 1px solid #ddd;
  padding: 10px;
  width: 200px;
  text-align: center;
}