Created
October 16, 2021 04:11
-
-
Save yarigpopov/094f4dc71e6d6c745eb3c5a3b1e67258 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { useMachine } from "@xstate/react"; | |
import async from "./async-machine"; | |
function noop() {} | |
function useAsync({ trigger, onSuccess, onError } = {}) { | |
const [current, send] = useMachine( | |
async.withContext({ | |
trigger: trigger || noop, | |
onSuccess: onSuccess || noop, | |
onError: onError || noop | |
}) | |
); | |
return { | |
trigger: send.bind(null, { type: "DO" }), | |
current, | |
isIdle: current.matches("idle"), | |
isBusy: current.matches("busy"), | |
didSucceed: current.matches("success"), | |
didError: current.matches("error") | |
}; | |
} | |
export default useAsync; |
This file contains hidden or 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
import React from "react"; | |
import useAsync from "./use-async"; | |
function AsyncHooks(props) { | |
const { current, isBusy, trigger } = useAsync({ trigger: props.trigger }); | |
return ( | |
<div> | |
<div>{current.value}</div> | |
<button type="button" disabled={isBusy} onClick={trigger}> | |
click | |
</button> | |
</div> | |
); | |
} | |
export default AsyncHooks; |
This file contains hidden or 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
import React from 'react'; | |
import AsyncHooks from './AsyncHooks'; | |
import asyncThing from './async-thing'; | |
export default function App() { | |
return ( | |
<div className="App"> | |
<div> | |
<h1>React - Async hooks</h1> | |
<AsyncHooks trigger={asyncThing} /> | |
</div> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment