react hooks port requst

Solutions on MaxInterview for react hooks port requst by the best coders in the world

showing results for - "react hooks port requst"
Serena
02 Oct 2016
1export default function App() {
2  const [data, setData] = useState([])
3  const [formData, setFormData] = useState('')
4
5  useEffect(() => {
6    fetchGames() // Fetch games when component is mounted
7  }, [])
8
9  const fetchGames = () => {
10    fetch('http://localhost:3000/game', {
11      method: 'GET',
12    })
13      .then((res) => res.json())
14      .then((result) => setData(result.rows))
15      .catch((err) => console.log('error'))
16  }
17
18  const saveGames = () => {
19    fetch('http://localhost:3000/game', {
20      method: 'POST',
21      headers: {
22        'Content-Type': 'application/json',
23      },
24      body: JSON.stringify({
25        name: formData, // Use your own property name / key
26      }),
27    })
28      .then((res) => res.json())
29      .then((result) => setData(result.rows))
30      .catch((err) => console.log('error'))
31  }
32
33  const handleSubmit = (event) => {
34    event.preventDefault()
35    saveGames() // Save games when form is submitted
36  }
37
38  const handleChange = (event) => {
39    setFormData(event.target.value)
40  }
41
42  return (
43    <div className="App">
44      {/* method="post" not needed here because `fetch` is doing the POST not the `form` */}
45      {/* Also, note I changed the function name, handleSubmit */}
46      <form onSubmit={handleSubmit}>
47        <input type="text" name="name" value={formData} onChange={handleChange} />
48        <button type="submit">click</button>
49      </form>
50
51      {data &&
52        data.map((element, index) => (
53          <GameTestResult name={element.name} key={element.index} />
54        ))}
55    </div>
56  )
57}
58
similar questions
queries leading to this page
react hooks port requst