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
|
import React, { useEffect, useReducer } from "react";
import "./App.css";
import axios from "axios";
const initialState = {
loading: true,
error: "",
post: {},
};
const reducer = (state, action) => {
switch (action.type) {
case "FETCH_SUCCESS":
return {
loading: false,
post: action.payload,
error: "",
};
case "FETCH_ERROR":
return {
loading: true,
post: {},
error: "データの取得に失敗しました。",
};
default:
return state;
}
};
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
if (state.loading) {
axios
.get("https://jsonplaceholder.typicode.com/posts/1")
.then((res) => {
dispatch({ type: "FETCH_SUCCESS", payload: res.data });
})
.catch((err) => {
dispatch({ type: "FETCH_ERROR" });
});
}
});
return (
<div className="App">
<h1>{state.loading ? "Loading..." : state.post.title}</h1>
<h2>{state.error ? state.error : null}</h2>
</div>
);
}
export default App;
|