-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
useAsync
is untyped. Um, I don't have a pull request but here is one of mine that you could could probably crib from.
export const useAsync = <S, T>(asyncFn: (parametersObject: S) => Promise<T>, parametersObject: S) => {
const [result, setResult] = useState<[T?, boolean?, Error?]>([undefined, true, undefined]);
const newInput = useMemo<S>(() => parametersObject, Object.values(parametersObject));
const changedInput = useDebounce(newInput, 100);
const reload = useCallback(() => {
setResult([result[0], true, undefined]); // don't clear out Data on new call; makes UX less jumpy
asyncFn(changedInput)
.then(data => setResult([data, false, undefined]))
.catch(err => setResult([undefined, false, err]));
}, [changedInput, asyncFn]);
useEffect(reload, [changedInput]); // don't auto-call if asyncFn changed cause it might be an inline lambda
return (result as any[]).concat(reload) as [T | undefined, boolean, Error | undefined, () => void];
};
usage: const [response, isLoading, error, reload] = useAsync(fetchData, { columns, sorting, paging, searchText });
It has a smaller featureset than yours and the invocation is less verbose, and I never truly solved the typing issue on the return statement, but from the outside it's nice. The dependency array is an object instead of an array.
Metadata
Metadata
Assignees
Labels
No labels