-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathindex.tsx
83 lines (78 loc) · 2.24 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import useStateMachine, {t} from '@cassiozen/usestatemachine';
import './index.css';
import Cup from './Cup';
/*
* In this example we're fetching some data with included retry logic (Will retry 2 times before giving up)
*/
type Coffee = {
id: number;
title: string;
description: string;
ingredients: string[];
};
function App() {
const [machine, send] = useStateMachine({
schema: {
context: t<{ retryCount: number; data?: Coffee[]; error?: string }>()
},
context: { retryCount: 0 },
initial: 'loading',
verbose: true,
states: {
loading: {
on: {
SUCCESS: 'loaded',
FAILURE: 'error',
},
effect({ setContext }) {
const fetchCoffees = async () => {
let response: Response;
try {
response = await fetch('https://api.sampleapis.com/coffee/hot');
if (!response.ok) {
throw new Error(`An error has occured: ${response.status}`);
}
const coffees = await response.json();
setContext(context => ({ data: coffees, ...context })).send('SUCCESS');
} catch (error) {
setContext(context => ({ error: error.message, ...context })).send('FAILURE');
}
};
fetchCoffees();
},
},
loaded: {},
error: {
on: {
RETRY: {
target: 'loading',
guard: ({ context }) => context.retryCount < 3,
},
},
effect({ setContext }) {
setContext(context => ({ ...context, retryCount: context.retryCount + 1 })).send('RETRY');
},
},
},
});
return (
<div className="coffees">
<Cup />
{machine.value === 'loading' && <p>Loading</p>}
{machine.value === 'error' && <p>{machine.context.error}</p>}
{machine.value === 'loaded' && (
<ul>
{machine.context.data?.map(coffee => (
<li key={coffee.id}>
<h2>{coffee.title}</h2>
<p>{coffee.description}</p>
</li>
))}
</ul>
)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));