-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
87 lines (77 loc) · 2.13 KB
/
App.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
84
85
86
87
import React, {useEffect, useState} from 'react';
import {
ActivityIndicator,
FlatList,
ListRenderItemInfo,
StyleSheet,
Text,
View,
} from 'react-native';
import {EpisodeItem} from './src/components/EpisodeItem';
import {Episode, Info} from './src/models/interfaces';
import axios from 'axios';
import {colors} from './src/theme/colors';
import {FixedHeader} from './src/components/FixedHeader';
export default function App() {
const [list, setList] = useState<Episode[]>([]);
const [page, setPage] = useState(1);
const [hasMoreData, setHasMoreData] = useState(true);
function renderItem({item}: ListRenderItemInfo<Episode>) {
return <EpisodeItem {...item} />;
}
async function getCharacters() {
// remova o comentário do setTimeout para perceber o loading com o delay
// setTimeout(async () => {
if (!hasMoreData) return;
const {data} = await axios.get<Info<Episode[]>>(
`https://rickandmortyapi.com/api/episode?page=${page}`,
);
if (data.results) {
const current = data.results;
setList(prev => [...prev, ...current]);
if (data.info?.next) {
setPage(prev => prev + 1);
} else {
setHasMoreData(false);
}
}
// }, 2000);
}
useEffect(() => {
getCharacters();
}, []);
return (
<View style={styles.container}>
<FixedHeader />
<FlatList
ListHeaderComponent={<Text style={styles.title}>Rick and Morty</Text>}
data={list}
contentContainerStyle={{paddingBottom: 20}}
keyExtractor={item => item.name}
renderItem={renderItem}
onEndReached={getCharacters}
onEndReachedThreshold={0.1}
ListFooterComponent={<Loading loading={hasMoreData} />}
/>
</View>
);
}
function Loading({loading}: {loading: boolean}) {
if (loading) {
return <ActivityIndicator size={'large'} color={colors.primary} />;
}
return null;
}
const styles = StyleSheet.create({
container: {
backgroundColor: colors.background,
flex: 1,
},
title: {
alignSelf: 'center',
fontSize: 36,
fontWeight: 'bold',
color: colors.onBackground,
marginVertical: 16,
},
});