Skip to content

Instantly share code, notes, and snippets.

View myWsq's full-sized avatar
🎯
Focusing

Shuaiqi Wang myWsq

🎯
Focusing
View GitHub Profile
@myWsq
myWsq / use-async-react.js
Last active April 7, 2020 11:21
[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);
export function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number,
immediate = false
) {
let timeout: number | undefined;
return function (this: any, ...args: Parameters<T>) {
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = undefined;