Skip to content

Instantly share code, notes, and snippets.

@myWsq

myWsq/use-async-react.js

Last active Apr 7, 2020
Embed
What would you like to do?
[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