simple diary : refactoring - useReducer

This commit is contained in:
haerong22
2022-04-15 20:43:34 +09:00
parent 6ccea03ba3
commit 8ecea4223a
2 changed files with 45 additions and 24 deletions

View File

@@ -1,6 +1,6 @@
import React, {
useRef,
useState,
useReducer,
useEffect,
useMemo,
useCallback,
@@ -9,8 +9,37 @@ import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";
const reducer = (state, action) => {
switch (action.type) {
case "INIT": {
return action.data;
}
case "CREATE": {
const created_date = new Date().getTime();
const newItem = {
...action.data,
created_date,
};
return [newItem, ...state];
}
case "REMOVE": {
return state.filter((it) => it.id !== action.targetId);
}
case "EDIT": {
return state.map((it) =>
it.id === action.targetId ? { ...it, content: action.newContent } : it
);
}
default:
return state;
}
};
const App = () => {
const [data, setData] = useState([]);
// const [data, setData] = useState([]);
const [data, dispatch] = useReducer(reducer, []);
const dataId = useRef(0);
@@ -29,7 +58,7 @@ const App = () => {
};
});
setData(initData);
dispatch({ type: "INIT", data: initData });
};
useEffect(() => {
@@ -37,31 +66,27 @@ const App = () => {
}, []);
const onCreate = useCallback((author, content, emotion) => {
const created_date = new Date().getTime();
dispatch({
type: "CREATE",
data: {
author,
content,
emotion,
id: dataId.current,
},
});
const newItem = {
author,
content,
emotion,
created_date,
id: dataId.current,
};
dataId.current += 1;
setData((data) => [newItem, ...data]);
}, []);
const onRemove = useCallback((targetId) => {
alert(`${targetId}가 삭제되었습니다.`);
setData((data) => data.filter((it) => it.id !== targetId));
dispatch({ type: "REMOVE", targetId });
}, []);
const onEdit = useCallback((targetId, newContent) => {
setData((data) =>
data.map((it) =>
it.id === targetId ? { ...it, content: newContent } : it
)
);
dispatch({ type: "EDIT", targetId, newContent });
}, []);
const getDiaryAnalysis = useMemo(() => {

View File

@@ -1,4 +1,4 @@
import React, { useRef, useState, useEffect } from "react";
import React, { useRef, useState } from "react";
const DiaryItem = ({
onEdit,
@@ -9,10 +9,6 @@ const DiaryItem = ({
emotion,
id,
}) => {
useEffect(() => {
console.log(`${id}번 째 아이템 렌더`);
});
const [isEdit, setIsEdit] = useState(false);
const [localContent, setLocalContent] = useState(content);