|
1 | 1 | import { useStarships } from "@/hooks/useStarships"; |
2 | | -import { useId } from "react"; |
| 2 | +import { UseQueryResult } from "@tanstack/react-query"; |
3 | 3 | import { StyleSheet, View } from "react-native"; |
4 | 4 | import { Text } from "react-native-paper"; |
5 | 5 |
|
6 | 6 | interface StarshipLoadableListProps { |
7 | 7 | starships: string[]; |
8 | 8 | } |
9 | 9 |
|
10 | | -function getRandom(max: number) { |
11 | | - return Math.floor(Math.random() * max); |
| 10 | +function randomId() { |
| 11 | + return Math.random().toString(36).substring(7); |
| 12 | +} |
| 13 | + |
| 14 | +function StarshipLoadableListItem({ |
| 15 | + result, |
| 16 | +}: { |
| 17 | + result: UseQueryResult<any, Error>; |
| 18 | +}) { |
| 19 | + if (result.isLoading) { |
| 20 | + return <Text variant="bodyMedium">Loading…</Text>; |
| 21 | + } |
| 22 | + |
| 23 | + if (result.isError) { |
| 24 | + return <Text variant="bodyMedium">Error 😕</Text>; |
| 25 | + } |
| 26 | + |
| 27 | + return ( |
| 28 | + <View style={styles.container}> |
| 29 | + <Text variant="titleMedium">{result.data.name}</Text> |
| 30 | + <Text variant="bodyMedium">{result.data.model}</Text> |
| 31 | + </View> |
| 32 | + ); |
12 | 33 | } |
13 | 34 |
|
14 | 35 | export const StarshipLoadableList = ({ |
15 | 36 | starships, |
16 | 37 | }: StarshipLoadableListProps) => { |
17 | 38 | const queryResult = useStarships(starships); |
18 | | - const id = useId(); |
19 | 39 |
|
20 | 40 | return queryResult.map((result) => { |
21 | | - if (result.isLoading) { |
22 | | - return ( |
23 | | - <Text |
24 | | - key={id} |
25 | | - variant="bodyMedium" |
26 | | - > |
27 | | - Loading… |
28 | | - </Text> |
29 | | - ); |
30 | | - } |
31 | | - |
32 | | - if (result.isError) { |
33 | | - return ( |
34 | | - <Text |
35 | | - key={id} |
36 | | - variant="bodyMedium" |
37 | | - > |
38 | | - Error 😕 |
39 | | - </Text> |
40 | | - ); |
41 | | - } |
42 | | - |
| 41 | + const id = randomId(); |
43 | 42 | return ( |
44 | | - <View |
45 | | - key={getRandom(1000)} |
46 | | - style={styles.container} |
47 | | - > |
48 | | - <Text variant="titleMedium">{result.data.name}</Text> |
49 | | - <Text variant="bodyMedium">{result.data.model}</Text> |
50 | | - </View> |
| 43 | + <StarshipLoadableListItem |
| 44 | + key={id} |
| 45 | + result={result} |
| 46 | + /> |
51 | 47 | ); |
52 | 48 | }); |
53 | 49 | }; |
|
0 commit comments