How to get a component when client does not fetches the data from API ?
When constructing a React application, incorporating data from an API is standard practice for dynamic content display. Yet, there are instances where the data isn’t immediately accessible during the initial component rendering. It becomes crucial to adeptly manage situations where data retrieval is pending, ensuring a seamless user experience by presenting loading or error messages as needed.
Prerequisites:
useState Hook: The `useState` React Hook facilitates the addition of a state variable to your component. The first parameter represents the initial state, while the second is a function employed for updating the state.
Syntax:
const [state, setState] = useState(initialstate)
useEffect Hook: The `useEffect` React Hook serves as a mechanism for synchronizing a component with an external system, enabling the execution of side effects. Examples of these effects include data fetching, and manual manipulation of the DOM within React components.
Syntax:
useEffect(setup, dependencies?)
Approach:
- In React.js, you can return a component that shows a loading message or a fallback component when the data is not yet fetched from the API. This can be done using conditional rendering based on the state of the data.
- In the following example, we have a component that fetches data from an API and displays it in a list. However, if the data is not yet available when the component is first rendered, it will throw an error because it is trying to map over an undefined state variable.
Steps to Create React Application And Installing Module:
Step 1: Run the following command to initialize a new React project:
npx create-react-app my-app
Step 2: Navigate into the newly created project directory :
cd my-app
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example 1: In this example, the use effect is used to call an API and set the response or error in the component’s state. The component then returns a message based on the current state (either an error message, a loading message, or the response from the API).
Javascript
import React, { useState, useEffect } from 'react' ; const Example = () => { const [response, setResponse] = useState( null ); const [error, setError] = useState( null ); useEffect(() => { fetch( 'https://api...com/data' ) .then(res => res.json()) .then(data => setResponse(data)) . catch (error => setError(error)); }, []); if (error) { return <div> An error occurred: {error.message} </div>; } else if (!response) { return <div>Loading...</div>; } else { return <div> Response from API: {JSON.stringify(response)} </div>; } }; export default Example; |
Output:
Example 2:
- Import
useState
anduseEffect
from React to manage component state and side effects. - Create a stateless functional component named
App
with two state variables:data
anderror
. - Use
useEffect
to fetch data from the API during component mount, replacing ‘YOUR-API-KEY‘ with a unique key. - Implement conditional statements to handle error and loading states, and export
App
as the default module export.
Javascript
import React, { useState, useEffect } from "react" ; const App = () => { const [data, setData] = useState( null ); const [error, setError] = useState( null ); console.log(data); useEffect(() => { fetch( "https://api.spoonacular.com/recipes/complexSearch?apiKey=YOUR_API_KEY" ) .then((res) => res.json()) .then((data) => setData(data)) . catch ((error) => setError(error)); }, []); if (error) { return <div> An error occurred: {error.message} </div>; } else if (!data) { return <h2>Loading...</h2>; } else { return ( <div> <h1>Recipes</h1> <ul> {data.results.map((item) => ( <li key={item.id}> <p>{item.title}</p> <img src={item.image} alt= "img" /> </li> ))} </ul> </div> ); } }; export default App; |
Output: The below output shows the ‘Loading…‘ component until the data is being fetched and displayed on the screen.
Contact Us