인프런 커뮤니티 질문&답변

작성자 없음

작성자 정보가 삭제된 글입니다.

[2024] 한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지

12.10) Home 페이지 구현하기 1. UI

onCreate is not a function 에러

해결된 질문

22.03.31 15:21 작성

·

430

0

안녕하세요 이정환 강사님! 강의 정말 잘 듣고 따라서 열심히 만들고 있습니다 다름이 아니라 강사님 강의를 보고 따라서 만들다가 오류를 만났는데 오류 잡기가 너무 어려워서 질문 남겨요.

강의 39분 부터 시작되는 작성완료 부분에서 글을 쓰고 작성완료를 누르면 홈으로 이동은 하는데 글이 등록이 되지 않습니다

 

제가 작성한 오류 관련 부분 DiaryEditor.js, App.js 코드 남겨드립니다

 

DiaryEditor.js

import { useNavigate } from "react-router-dom";
import { useContext, useRef, useState } from "react";
import { DiaryDispatchContext } from "./../App.js";

import MyHeader from "./MyHeader";
import MyButton from "./MyButton";
import EmotionItem from "./EmotionItem";

const emotionList = [
  {
    emotion_id: 1,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion1.png`,
    emotion_descript: "best",
  },
  {
    emotion_id: 2,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion2.png`,
    emotion_descript: "good",
  },
  {
    emotion_id: 3,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion3.png`,
    emotion_descript: "not bad",
  },
  {
    emotion_id: 4,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion4.png`,
    emotion_descript: "bad",
  },
  {
    emotion_id: 5,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion5.png`,
    emotion_descript: "worst",
  },
];

const getStringDate = (date) => {
  return date.toISOString().slice(0, 10);
};

const DiaryEditor = () => {
  const contentRef = useRef();
  // 오늘의 일기를 state에 mapping 하기 위한 state
  const [content, setContent] = useState("");
  // 어떤 감정을 선택했는지 저장할 state
  const [emotion, setEmotion] = useState(3);
  const [date, setDate] = useState(getStringDate(new Date()));

  const { onCreate } = useContext(DiaryDispatchContext);
  // emotion을 클릭하면 수행할 함수
  const handleClickEmote = (emotion) => {
    setEmotion(emotion);
  };

  const navigate = useNavigate();

  //작성완료 버튼의 기능
  const handleSubmit = () => {
    if (content.length < 1) {
      contentRef.current.focus();
      return;
    }
    //context length가 적절한 길이가 되었을때 onCreate 함수를 호출
    onCreate(date, content, emotion);
    navigate("/", { replace: true });
  };

  return (
    <div className="DiaryEditor">
      <MyHeader
        headText={"write a diary"}
        leftChild={<MyButton text={"< back"} onClick={() => navigate(-1)} />}
      />
      <div>
        {/* 역할은  div와 동일한데 이름만 다르다 */}
        <section>
          <h4>Date</h4>
          <div className="input_box">
            {/* 날자 선택이 가능한 html 태그 */}
            <input
              value={date}
              onChange={(e) => setDate(e.target.value)}
              className="input_date"
              type="date"
            />
          </div>
        </section>
        <section>
          <h4>Feeling</h4>
          <div className="input_box emotion_list_wrapper">
            {emotionList.map((it) => (
              <EmotionItem
                key={it.emotion_id}
                {...it}
                onClick={handleClickEmote}
                //emotion감정이 선택된 감정인지 아닌지를 알게하기 위한 prop
                // 선택된 emotion의 값과 같은 emtion = true, 같지 않은 emotion = false
                isSelected={it.emotion_id === emotion}
              />
            ))}
          </div>
        </section>
        <section>
          <div className="input_box text_wrapper">
            <textarea
              placeholder="How was your day?"
              ref={contentRef}
              value={content}
              onChange={(e) => setContent(e.target.value)}
            ></textarea>
          </div>
        </section>
        <section>
          <div className="control-box">
            <MyButton text={"save"} type={"positive"} onClick={handleSubmit} />
          </div>
        </section>
      </div>
    </div>
  );
};

export default DiaryEditor;

App.js

import React, { useReducer, useRef } from "react";

import "./App.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";

import Home from "./pages/Home";
import New from "./pages/New";
import Edit from "./pages/Edit";
import Diary from "./pages/Diary";

const reducer = (state, action) => {
  let newState = [];
  switch (action.type) {
    case "INIT": {
      return action.data;
    }
    case "CREATE": {
      newState = [action.data, ...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;
};

export const DiaryStateContext = React.createContext();
export const DiaryDispatchContext = React.createContext();

const dummyData = [
  {
    id: 1,
    emotion: 1,
    content: "오늘의일기 1번",

    date: 1648633885549,
  },
  {
    id: 2,
    emotion: 2,
    content: "오늘의일기 2번",

    date: 1648633885550,
  },
  {
    id: 3,
    emotion: 3,
    content: "오늘의일기 2번",

    date: 1648633885551,
  },
  {
    id: 4,
    emotion: 4,
    content: "오늘의일기 4번",

    date: 1648633885552,
  },
  {
    id: 5,
    emotion: 5,
    content: "오늘의일기 5번",

    date: 1648633885553,
  },
];

function App() {
  const [data, dispatch] = useReducer(reducer, dummyData);

  console.log(new Date().getTime());

  const dataId = useRef(0);

  const onCreate = (date, content, emotion) => {
    dispatch({
      type: "CREATE",
      data: {
        id: dataId.current,
        date: new Date(date).getTime(),
        content,
        emotion,
      },
    });
    dataId.current += 1;
  };

  const onRemove = (targetId) => {
    dispatch({ type: "REMOVE", targetId });
  };

  const onEdit = (targetId, date, content, emotion) => {
    dispatch({
      type: "EDIT",

      data: {
        id: targetId,
        date: new Date(date).getTime(),
        content,
        emotion,
      },
    });
  };

  return (
    <DiaryStateContext.Provider value={data}>
      <DiaryDispatchContext.Provider value={{ onCreate, onRemove, onEdit }}>
        <BrowserRouter>
          <div className="App">
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/new" element={<New />} />
              <Route path="/edit/:id" element={<Edit />} />
              <Route path="/diary/:id" element={<Diary />} />
            </Routes>
          </div>
        </BrowserRouter>
      </DiaryDispatchContext.Provider>
    </DiaryStateContext.Provider>
  );
}

export default App;

답변 1

0

이정환 Winterlood님의 프로필 이미지
이정환 Winterlood
지식공유자

2022. 03. 31. 19:57

안녕하세요 강사 이정환입니다.

혹시 가능하시다면 CodeSandbox에 현재 코드를 업로드하여 링크로 전달 해 주실 수 있으실까요?

작성자 없음

작성자 정보가 삭제된 글입니다.

질문하기