Open In App

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:

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: 

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). 




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:

Output

Example 2:




import React, { useState, useEffect } from "react";
 
const App = () => {
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);
 
    console.log(data);
 
    useEffect(() => {
        fetch(
        )
            .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.

Output


Article Tags :