Open In App

How to handle asynchronous operations in custom hooks?

Custom Hooks in React are reusable JavaScript functions that enable the encapsulation of stateful logic, promoting cleaner and more modular code in components. When dealing with asynchronous operations in custom hooks, you want to ensure your hook can handle tasks that don’t finish immediately, like fetching data from a server or waiting for a user interaction.

Simple Approach to Handle Asynchronous operation:

Example: This is a simple example to handle asynchronous operations in custom hooks.




import React, {
    useState,
    useEffect
}
    from 'react';
 
// Custom hook for fetching data asynchronously
const useAsyncData = (url) => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
 
    useEffect(() => {
        async function fetchData() {
            try {
                setLoading(true);
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(
                        'Network response was not ok');
                }
                const jsonData = await response.json();
                setData(jsonData);
            } catch (error) {
                setError(error);
            } finally {
                setLoading(false);
            }
        }
 
        fetchData();
        return () => {
        };
    }, [url]);
    /*
     Depend on url so that useEffect
     runs whenever the url changes
    */
 
    return { data, loading, error };
}
 
const App = () => {
    const { data, loading, error } =
        useAsyncData('https://fakestoreapi.com/products');
 
    if (loading) {
        return <div>Loading...</div>;
    }
 
    if (error) {
        return <div>Error: {error.message}</div>;
    }
 
    return (
        <div>
            {/* Render your data */}
            {data && (
                <ul>
                    {data.map(item => (
                        <li key={item.id}>
                            {item.title}
                        </li>
                    ))}
                </ul>
            )}
        </div>
    );
}
 
export default App;

Output:

Ouput


Article Tags :