-
Notifications
You must be signed in to change notification settings - Fork 700
/
25-http.html
97 lines (86 loc) · 2.58 KB
/
25-http.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
<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>
<!--
The next two scripts don't appear in the videos.
To learn why these two scripts were added, read:
https://github.com/kentcdodds/beginners-guide-to-react/issues/3
-->
<script src="https://unpkg.com/[email protected]/lib/umd/index.js"></script>
<script src="/pokemon-api.js"></script>
<script type="text/babel">
function PokemonInfo({pokemonName}) {
const [pokemon, setPokemon] = React.useState(null)
React.useEffect(() => {
if (!pokemonName) {
return
}
fetchPokemon(pokemonName).then(pokemonData => {
setPokemon(pokemonData)
})
}, [pokemonName])
if (!pokemonName) {
return 'Submit a pokemon'
}
if (!pokemon) {
return '...'
}
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 PokemonInfo($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>