Generate a React custom hook for asynchronous functions
Private research annotation
Sign in to add a private research label or note.
- User
Generate a React custom hook for asynchronous functions
- Assistant
Here's a custom React hook for handling asynchronous functions. This hook,
useAsync, takes a function as an argument and returns the current status (loading, error, or success), as well as arunfunction to execute the provided async function.javascriptimport { useState, useCallback, useEffect } from 'react'; export function useAsync(asyncFunction, immediate = true) { const [status, setStatus] = useState('idle'); const [value, setValue] = useState(null); const [error, setError] = useState(null); const execute = useCallback( (...args) => { setStatus('pending'); setValue(null); setError(null); return asyncFunction(...args) .then(response => { setValue(response); setStatus('success'); }) .catch(error => { setError(error); setStatus('error'); }); }, [asyncFunction] ); useEffect(() => { if (immediate) { execute(); } }, [execute, immediate]); return { execute, status, value, error }; }Here's how you can use this
useAsynchook in a functional component:javascriptimport React from 'react'; import { useAsync } from './useAsync'; function fetchUser(id) { return fetch(`https://jsonplaceholder.typicode.com/users/${id}`).then(response => response.json() ); } function User({ userId }) { const { status, value: user, error } = useAsync(() => fetchUser(userId), true); if (status === 'loading') return <div>Loading...</div>; if (status === 'error') return <div>Error: {error.message}</div>; if (status === 'idle' || status === 'success') return <div>{user.name}</div>; } function App() { return <User userId={1} />; } export default App; - User
I prefer to use a reducer for the state
- Assistant
Here's an updated version of the
useAsynchook that uses theuseReducerhook to manage the state. This approach allows for better separation of concerns and easier state updates.javascript - User
Don't we need dependancies?
- Assistant
You're right, I apologize for missing the dependencies in the
useCallbackanduseEffecthooks. Here's the updated version of theuseAsynchook with the correct dependencies:javascript
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.