shockmap-api / frontend /src /hooks /useAsync.js
Dhruva P Gowda
Build ShockMap MVP, operator UI, and deployment scaffolding
f927995
Raw History Blame Contribute Delete
618 Bytes
import { useState, useEffect, useCallback } from 'react';
export function useAsync(fn, deps = []) {
const [state, setState] = useState({ data: null, loading: true, error: null });
const run = useCallback(async () => {
setState(s => ({ ...s, loading: true, error: null }));
try {
const data = await fn();
setState({ data, loading: false, error: null });
} catch (e) {
setState({ data: null, loading: false, error: e.message });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
useEffect(() => { run(); }, [run]);
return { ...state, refetch: run };
}