App.js
import {useReducer, useRef} from 'react';
const reducer = (state, action) => {
let newState = [];
switch(action.type){
case 'INIT' : {
return action.data;
}
case 'CREATE' : {
newState = [action.date, ...state];
break;
}
case 'REMOVE' : {
newState = state.filter((it)=>it.id !== action.targetId);
break;
}
case 'EDIT' : {
newState = state.map((it)=>it.id === action.data.id? {...action.data}:it);
break;
}
default:
return state;
}
return newState;
}
const [data, dispath] = useReducer(reducer, []);
const dataId = useRef(0);
//CREATE
const onCreate = (date,content,emotion) => {
dispath({
type:'CREATE',
data:{
id:dataId.current,
date:new Date(date).getTime(),
content,
emotion,
}
});
dataId.current += 1;
}
//REMOVE
const onRemove = (targetId) => {
dispath({
type:'REMOVE',
targetId
})
}
//EDIT
const onEdit = (targetId,date,content,emotion) => {
dispath({
type:'EDIT',
data:{
id:targetId,
date:new Date(date).getTime(),
content,
emotion,
}
})
}
import React,{useReducer, useRef} from 'react';
export const DiaryStateContext = React.createContext();
return (
<DiaryStateContext.Provider value={data}>
<BrowserRouter>
<div className="App">
<Routes>
<Route path="/" element={<Home/>}></Route>
<Route path="/new" element={<New/>}></Route>
<Route path="/edit" element={<Edit/>}></Route>
<Route path="/diary/:id" element={<Diary/>}></Route>
</Routes>
</div>
</BrowserRouter>
</DiaryStateContext.Provider>
);
export const DiaryDispatchContext = React.createContext();
return (
<DiaryStateContext.Provider value={data}>
<DiaryDispatchContext.Provider value={{
onEdit,
onCreate,
onRemove,
}}>
<BrowserRouter>
<div className="App">
<Routes>
<Route path="/" element={<Home/>}></Route>
<Route path="/new" element={<New/>}></Route>
<Route path="/edit" element={<Edit/>}></Route>
<Route path="/diary/:id" element={<Diary/>}></Route>
</Routes>
</div>
</BrowserRouter>
</DiaryDispatchContext.Provider>
</DiaryStateContext.Provider>
);