Last active
December 31, 2022 05:56
-
-
Save idiotWu/f82bd2f750873ebd1071380c39d69dbd to your computer and use it in GitHub Desktop.
useSignal() Hook
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
const initialState = { | |
activated: false, | |
resolve: () => {}, | |
}; | |
function useSignal() { | |
const [state, setState] = useState(initialState); | |
function init() { | |
return new Promise((resolve) => { | |
setState({ | |
activated: true, | |
resolve, | |
}); | |
}); | |
} | |
function ok() { | |
state.resolve(true); | |
setState(initialState); | |
} | |
function cancel() { | |
state.resolve(false); | |
setState(initialState); | |
} | |
return { | |
init, | |
ok, | |
cancel, | |
activated: state.activated, | |
}; | |
} | |
// usage | |
function FormApp() { | |
const signal = useSignal(); | |
async function submit() { | |
const confirmed = await signal.init(); | |
if (confirmed) { | |
// do something | |
} else { | |
// do something else | |
} | |
} | |
return ( | |
<div> | |
<button onClick={submit}>Submit</button> | |
<Dialog open={signal.activated}> | |
<button onClick={signal.ok}>OK</button> | |
<button onClick={signal.cancel}>Cancel</button> | |
</Dialog> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment