In this article, we will learn how to fetch and iterate over data in Reactjs.
React is the most popular DOM manipulation library out here at the moment, thanks to its near-native implementation of HTML DOM using JSX and support for native JavaScript syntax, making it is easier to learn and get started with.
In React, if you have to fetch the data by making API calls and render them on the DOM you will have to make use of the 3 things.
1. useEffect() to make the API call when the component mounts.
2. useState() to persist the data fetched from the network
3. General array methods like maps form a list of the items so that it can be rendered.
import { useEffect, useState } from "react"; const App = () => { const [data, setData] = useState([]); useEffect(() => { const makeApiCall = async () => { try { let response = await fetch( "https://jsonplaceholder.typicode.com/todos" ); response = await response.json(); setData(response); } catch (e) { console.error("Error while fetching data", e); } }; makeApiCall(); }, []); return ( <div className="App"> {data.length === 0 ? ( <p>...loading</p> ) : ( data.map((entry) => { return <p key={entry.id}>{entry.title}</p>; }) )} </div> ); }; export default App;
As during the component re-render, variable are redefined, React uses useState() to persist the values, also useEffect() hook is invoked at different stages of component lifecycle like mounting, unmounting, and update.
We are making the API call on the mount and persisting the data in useState().
Because we are using JSX, we can write native JavaScript in that and while rendering the JSX, React will convert an array of elements to actual DOM elements.