Created
September 22, 2021 23:00
-
-
Save joeldenning/ecd67557356f05071b5061813385d7e2 to your computer and use it in GitHub Desktop.
use imperative action
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useImperativeAction(action) { | |
const [status, setStatus] = useState(1); | |
useEffect(() => { | |
// negative means just cancel without re-running | |
if (status >= 0) { | |
return action(); | |
} | |
}, [status]); | |
const doAction = useCallback(() => { | |
setStatus((oldStatus) => { | |
if (oldStatus < 0) { | |
// positive means cancel last and re-run action | |
setStatus(1); | |
} else { | |
// ensure we don't set to the same value as before | |
setStatus(oldStatus + 1); | |
} | |
}); | |
}, []); | |
const cancel = useCallback(() => { | |
// negative means just cancel without re-running | |
setStatus(-1); | |
}, []); | |
return [doAction, cancel]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment