한입크기 감정일기장 - 프로젝트기초공사2

임하나·2023년 3월 24일
0

한입크기리액트

목록 보기
21/21

state 관리 로직만들기

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,
    }
  })
}

상태관리로직에 context만들고, 데이터 공급하기

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>
  );

0개의 댓글