forked from kentcdodds/beginners-guide-to-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
26-http-errors.html
105 lines (94 loc) · 2.69 KB
/
26-http-errors.html
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
99
100
101
102
103
104
105
<body>
<div id="root"></div>
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
<script type="text/babel">
function PokemonInfo({pokemonName}) {
const [status, setStatus] = React.useState('idle')
const [pokemon, setPokemon] = React.useState(null)
const [error, setError] = React.useState(null)
React.useEffect(() => {
if (!pokemonName) {
return
}
setStatus('pending')
fetchPokemon(pokemonName).then(
pokemonData => {
setStatus('resolved')
setPokemon(pokemonData)
},
errorData => {
setStatus('rejected')
setError(errorData)
},
)
}, [pokemonName])
if (status === 'idle') {
return 'Submit a pokemon'
}
if (status === 'rejected') {
return 'Oh no...'
}
if (status === 'pending') {
return '...'
}
if (status === 'resolved') {
return <pre>{JSON.stringify(pokemon, null, 2)}</pre>
}
}
function App() {
const [pokemonName, setPokemonName] = React.useState('')
function handleSubmit(event) {
event.preventDefault()
setPokemonName(event.target.elements.pokemonName.value)
}
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="pokemonName">Pokemon Name</label>
<div>
<input id="pokemonName" />
<button type="submit">Submit</button>
</div>
</form>
<hr />
<PokemonInfo pokemonName={pokemonName} />
</div>
)
}
function fetchPokemon(name) {
const pokemonQuery = `
query ($name: String) {
pokemon(name: $name) {
id
number
name
attacks {
special {
name
type
damage
}
}
}
}
`
return window
.fetch('https://graphql-pokemon.now.sh', {
// learn more about this API here: https://graphql-pokemon.now.sh/
method: 'POST',
headers: {
'content-type': 'application/json;charset=UTF-8',
},
body: JSON.stringify({
query: pokemonQuery,
variables: {name},
}),
})
.then(r => r.json())
.then(response => response.data.pokemon)
}
ReactDOM.render(<App />, document.getElementById('root'))
</script>
</body>