Skip to content

useAsync is untyped #10

@RonNewcomb

Description

@RonNewcomb

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions