Skip to content

Instantly share code, notes, and snippets.

@shinyoshiaki
Created December 11, 2019 10:47
Show Gist options
  • Select an option

  • Save shinyoshiaki/5c079825c0d347f78c8605db4564da07 to your computer and use it in GitHub Desktop.

Select an option

Save shinyoshiaki/5c079825c0d347f78c8605db4564da07 to your computer and use it in GitHub Desktop.
import { useState } from "react";
export function useLoading<A, B extends any[]>(
func: (...args: B) => Promise<A>
): [() => Promise<A | void>, boolean, string] {
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const fetch = async (...args: B) => {
setLoading(true);
const res = await func(...args).catch(e => {
setError(e);
});
setLoading(false);
return res;
};
return [fetch, loading, error];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment