-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpRandomCat.tsx
More file actions
73 lines (61 loc) · 1.53 KB
/
HttpRandomCat.tsx
File metadata and controls
73 lines (61 loc) · 1.53 KB
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
import {
Cmd,
exhaustiveCheck,
Init,
Sub,
Tea,
Update,
View,
} from '@foo-x/react-tea';
import { Dispatch } from 'react';
const baseUrl = 'https://cataas.com/cat';
const jsonUrl = `${baseUrl}?json=true`;
type Model = string;
type Msg = { type: 'fetch-cat' } | { type: 'set-src'; src: string };
type Props = unknown;
export const init: Init<Model, Msg, Props> = () => [
'',
Cmd.perform(
() => {
return {
type: 'fetch-cat',
};
},
async () => {},
),
];
const fetchCat = async (dispatch: Dispatch<Msg>) => {
const response = await fetch(jsonUrl);
const json = await response.json();
dispatch({ type: 'set-src', src: `${baseUrl}/${json._id}` });
};
export const update: Update<Model, Msg, Props> = ({ model, msg }) => {
switch (msg.type) {
case 'fetch-cat':
return [model, Cmd.promise(fetchCat)];
case 'set-src':
return [msg.src, Cmd.none()];
default:
return exhaustiveCheck(msg);
}
};
export const subscriptions: Sub<Model, Msg, Props> = Sub.none();
export const view: View<Model, Msg, Props> = ({ model, dispatch }) => {
return (
<div>
<h2>HTTP random cat</h2>
<button
type='button'
onClick={() => {
dispatch({ type: 'fetch-cat' });
}}
style={{ marginBottom: '1rem' }}
>
fetch new one
</button>
{model && <img src={model} alt='cat' style={{ maxWidth: '100%' }} />}
</div>
);
};
const HttpRandomCat = Tea({ init, update, subscriptions, view });
export default HttpRandomCat;