1. 일기 관리 기능 구현하기
- mockData 생성
- App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14
const mockData = [ { id: 1, createdDate: new Date().getTime(), emotionId: 1, // 감정은 1~5까지 존재 content: "1번 일기 내용", }, { id: 2, createdDate: new Date().getTime(), emotionId: 2, content: "2번 일기 내용", }, ];
- App.jsx
- reducer를 사용하여 일기 데이터 상태 생성
- App.jax ```jsx function reducer(state, action) { return state; }
function App() { const [data, dispatch] = useReducer(reducer, mockData); return ( <> …생략 </> ); }
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
3. 테스트 위한 임시 추가, 수정, 삭제 버튼
- App.jsx
```jsx
function reducer(state, action) {
switch (action.type) {
case "CREATE":
return [action.data, ...state];
case "UPDATE":
return state.map((item) =>
String(item.id) === String(action.data.id) ? action.data : item
);
case "DELETE":
return state.filter((item) => String(item.id) !== String(action.id));
default:
return state;
}
}
function App() {
const [data, dispatch] = useReducer(reducer, mockData);
const idRef = useRef(3);
// 새로운 일기 추가
const onCreate = (createdData, emotionId, content) => {
dispatch({
type: "CREATE",
data: {
id: idRef.current++,
createdData,
emotionId,
content,
},
});
};
// 기존 일기 수정
const onUpdate = (id, createdData, emotionId, content) => {
dispatch({
type: "UPDATE",
data: {
id,
createdData,
emotionId,
content,
},
});
};
// 기존 일기 삭제
const onDelete = (id) => {
dispatch({
type: "DELETE",
id,
});
};
return (
<>
<button
onClick={() => {
onCreate(new Date().getTime(), 1, "생성된 일기");
}}
>
일기 추가 테스트
</button>
<button
onClick={() => {
onUpdate(1, new Date().getTime(), 3, "수정된 일기");
}}
>
일기 수정 테스트
</button>
<button
onClick={() => {
onDelete(1);
}}
>
일기 삭제 테스트
</button>
...생략
</>
);
}
export default App;
- Context를 통해 모든 패이지에서 사용할 state와 함수 설정
- App.jsx ```jsx const DiaryStateContext = createContext(); const DiaryDispatchContext = createContext();
function App() { return ( <> …생략 <DiaryStateContext.Provider value={data}> <DiaryDispatchContext.Provider value=>