-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathApp.js
77 lines (65 loc) · 1.97 KB
/
App.js
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
import React, { Component } from 'react';
import { Button, StyleSheet, Text, ScrollView } from 'react-native';
import 'abortcontroller-polyfill';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
status: null,
data: null,
error: null
};
this.handleFetch = this.handleFetch.bind(this);
this.handleAbort = this.handleAbort.bind(this);
}
handleFetch() {
if (!AbortController) {
return this.setState({ status: 'Not implemented' });
}
this.controller = new window.AbortController();
this.signal = this.controller.signal;
this.setState({ status: 'loading...' });
fetch('https://swapi.co/api/people/1', { signal: this.signal })
.then((response) => response.json())
.then((data) => this.setState({ status: 'loaded', error: null, data }))
.catch((error) => this.setState({ error: error.name }));
}
handleAbort() {
this.controller.abort();
this.setState({ status: 'aborted' });
}
render() {
const { data, status, error } = this.state;
return (
<ScrollView style={styles.container}>
<Text style={styles.welcome}>
React Native + fetch + Abort Controller
</Text>
<Button title="Fetch data" onPress={this.handleFetch} />
<Button title="Abort" onPress={this.handleAbort} />
<Text style={styles.instructions}>{`Status: ${status}`}</Text>
<Text style={styles.instructions}>{`Error: ${error}`}</Text>
<Text style={styles.instructions}>Data</Text>
<Text style={styles.instructions}>{JSON.stringify(data, null, 2)}</Text>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
// justifyContent: 'center',
// alignItems: 'center',
backgroundColor: '#F5FCFF'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5
}
});