JSONPlayStore-API-Fetching-Mapping-In-React js
To use .map()
with fetch
in React, you need to follow these steps:
- Fetch Data from an API
- Store the Data in State
- 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:
Code Explanation
- State:
users
state is used to store the fetched data. - useEffect with Fetch:
fetch
retrieves data from the JSONPlaceholder API.- The response is parsed with
.json()
and stored inusers
viasetUsers
.
- Mapping through the Data:
users.map()
iterates over each user object.- Each
user
object is displayed withname
,email
, andcompany
properties