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:
usersstate is used to store the fetched data. - useEffect with Fetch:
fetchretrieves data from the JSONPlaceholder API.- The response is parsed with
.json()and stored inusersviasetUsers.
- Mapping through the Data:
users.map()iterates over each user object.- Each
userobject is displayed withname,email, andcompanyproperties