Skip to content

Instantly share code, notes, and snippets.

@yarigpopov
Created October 16, 2021 04:11
Show Gist options
  • Save yarigpopov/094f4dc71e6d6c745eb3c5a3b1e67258 to your computer and use it in GitHub Desktop.
Save yarigpopov/094f4dc71e6d6c745eb3c5a3b1e67258 to your computer and use it in GitHub Desktop.
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;
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;
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