forked from isaacplmann/sturdy-uis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathList.tsx
More file actions
98 lines (95 loc) · 2.69 KB
/
List.tsx
File metadata and controls
98 lines (95 loc) · 2.69 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { useMachine } from '@xstate/react';
import React, { useEffect } from 'react';
import { fetchMachine } from '../machines/fetch';
import { selectionMachine } from '../machines/select';
import './List.css';
function List({
fetchData,
selectedItem,
onSelection
}: {
fetchData: () => Promise<{ results: { name: string }[] }>;
selectedItem?: any;
onSelection?: (selectedItem: any) => void;
}) {
useEffect(() => {
sendToDataMachine({ type: 'FETCH' });
}, []);
const [dataMachine, sendToDataMachine] = useMachine(fetchMachine, {
actions: {
fetchData: () => {
fetchData()
.then(r => r.results)
.then(
results => {
sendToDataMachine({ type: 'RESOLVE', results });
},
message => {
sendToDataMachine({ type: 'REJECT', message });
}
);
},
notifyHasData: ctx => {
selectMachine.context.selectedIndex =
ctx.results &&
ctx.results.findIndex(
item => selectedItem && selectedItem.name === item.name
);
}
}
});
const [selectMachine, sendToSelectMachine] = useMachine(selectionMachine, {
actions: {
notifySelection: (ctx, event) => {
if (
dataMachine.context.results &&
ctx.selectedIndex !== undefined &&
onSelection
) {
onSelection(dataMachine.context.results[ctx.selectedIndex]);
}
}
}
});
return (
<>
<button onClick={() => sendToDataMachine({ type: 'FETCH' })}>
Fetch
</button>
{dataMachine.matches('idle') ? <p>Idle</p> : null}
{dataMachine.matches('pending') ? <p>Loading</p> : null}
{dataMachine.matches('fulfilled.withData') ? (
<ul>
{dataMachine.context.results &&
dataMachine.context.results.map((item, index) => (
<li
key={index}
className={
selectMachine.context.selectedIndex === index
? 'selected'
: ''
}
>
<button
className="selection-button"
onClick={() =>
sendToSelectMachine({
type: 'select',
selectedIndex: index
})
}
>
{item.name}
</button>
</li>
))}
</ul>
) : null}
{dataMachine.matches('fulfilled.withoutData') ? <p>No results</p> : null}
{dataMachine.matches('rejected') ? (
<p>{dataMachine.context.message}</p>
) : null}
</>
);
}
export default List;