JSONPlayStore-API-Fetching-Mapping-In-React js

To use .map() with fetch in React, you need to follow these steps:

  1. Fetch Data from an API
  2. Store the Data in State
  3. Map through the Data to display it

Here’s a complete example:

Step 1: Fetch and Map Data in a Component

For demonstration, let’s use App.js to fetch data from a mock API like JSONPlaceholder (for user data) or Fake Store API (for product data).

Here's an example using JSON Placeholder:

// App.js
import React, { useEffect, useState } from 'react';

export default function App() {
  const [users, setUsers] = useState([]);

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

  return (
    <div className="App">
      <h1>User List</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            <h2>{user.name}</h2>
            <p>Email: {user.email}</p>
            <p>Company: {user.company.name}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

Code Explanation
  1. State: users state is used to store the fetched data.
  2. useEffect with Fetch:
    • fetch retrieves data from the JSONPlaceholder API.
    • The response is parsed with .json() and stored in users via setUsers.
  3. Mapping through the Data:
    • users.map() iterates over each user object.
    • Each user object is displayed with name, email, and company properties