Skip to content

Instantly share code, notes, and snippets.

@myWsq
Last active April 7, 2020 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myWsq/25dbdff48220a84e21d819d5bcbbdd6d to your computer and use it in GitHub Desktop.
Save myWsq/25dbdff48220a84e21d819d5bcbbdd6d to your computer and use it in GitHub Desktop.
[useAsync] Keep track of the state of async function. #Vue #React #Hooks #CompositionAPI #Async #AsyncData #AsyncFunction
import { useState, useEffect, useCallback } from 'React'
const useAsync = (asyncFunc, immediate = true) => {
const [pending, setPending] = useState(0);
const [value, setValue] = useState(null);
const [error, setError] = useState(null);
const execute = useCallback(() => {
setPending(val => val + 1);
setValue(null);
setError(null);
return asyncFunc()
.then(response => setValue(response))
.catch(error => setError(error))
.finally(() => setPending(val => val - 1));
}, [asyncFunc]);
useEffect(() => {
if (immediate) {
execute();
}
}, [execute, immediate]);
return { execute, value, error, pending: pending > 0 };
};
import { ref, computed, reactive } from "@vue/composition-api";
export function useAsync(asyncFunc, immediate = true) {
const pendingCount = ref(0);
const pending = computed(() => pendingCount.value > 0);
const value = ref(null);
const error = ref(null);
function execute() {
pendingCount.value++;
value.value = null;
error.value = null;
return asyncFunc()
.then(res => (value.value = res))
.catch(err => (error.value = err))
.finally(() => pendingCount.value--);
}
if (immediate) {
execute();
}
return reactive({
pending,
value,
error,
execute
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment