Open In App

How to handle async operations with Custom Hooks ?

Handling asynchronous operations with custom Hooks involves using techniques like useState, useEffect, and asynchronous functions (async/await) to manage asynchronous logic within the Hook.

Handling Async operations with Custom Hooks:

Example: Below is an example of handling async operations with custom Hooks.




import React, {
    useState,
    useEffect
} from 'react';
 
function useAsyncOperation(url) {
    const [data, setData] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
 
    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true);
            try {
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const result = await response.json();
                setData(result);
            } catch (error) {
                setError(error);
            } finally {
                setIsLoading(false);
            }
        };
 
        fetchData();
        return () => {
        };
    }, [url]);
 
    return { data, isLoading, error };
}
function AsyncComponent() {
    const { data, isLoading, error } =
        useAsyncOperation('https://fakestoreapi.com/products');
 
    useEffect(() => {
        if (data) {
            console.log('Data fetched:', data);
        }
    }, [data]);
 
    useEffect(() => {
        if (error) {
            console.error('Error fetching data:', error);
        }
    }, [error]);
 
    return (
        <div>
            {isLoading && <p>Loading...</p>}
            {data && (
                <ul>
                    {data.map(item => (
                        <li key={item.id}>{item.title}
                            <b>Price</b> {item.price}
                        </li>
                    ))}
                </ul>
            )}
        </div>
    );
}
 
export default AsyncComponent;

Output:

Output


Article Tags :