Write an implementation of an async data call in a useEffect, set loading before and…
- User
Write an implementation of an async data call in a useEffect, set loading before and after the call, and set data depending on if a third variable is true when it returns. Be concise, just the hook
Assistant
import { useState, useEffect } from 'react'; function useAsyncData(asyncFunction, condition) { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (!condition) return; const fetchData = async () => { setLoading(true); setError(null); try { const result = await asyncFunction(); if (condition) { setData(result); } else { setData(null); // Reset data if condition is false after async call } } catch (err) { setError(err); } finally { setLoading(false); } }; fetchData(); }, [asyncFunction, condition]); return { data, loading, error }; } export default useAsyncData;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.