-
카테고리
-
세부 분야
풀스택
-
해결 여부
해결됨
Uncaught TypeError: Cannot read property '0' of undefined 에러가 발생합니다. 해결방법이 있을까요?
20.08.04 17:14 작성 조회수 2.07k
1
강좌 동영상에 같은 에러를 해결하시는 부분이 나오는데
app.js 에 '/posts' 동일한 라우터가 존재해서 삭제후 해결하시는 부분이
나오는데 .. 다른문제로 보입니다. routes/posts.js 파일 include Image 를 넣어주어도 해도 해결이 안되네요..
FRONT
pages/index.js
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import PostForm from '../components/PostForm';
import PostCard from '../components/PostCard';
import AppLayout from '../components/AppLayout';
import { LOAD_POSTS_REQUEST } from '../reducers/post';
import { LOAD_USER_REQUEST } from '../reducers/user';
const Home = () => {
const dispatch = useDispatch();
const { me } = useSelector((state) => state.user);
const { mainPosts, hasMorePosts, loadPostsLoading } = useSelector((state) => state.post);
useEffect(() => {
dispatch({
type: LOAD_USER_REQUEST,
})
dispatch({
type: LOAD_POSTS_REQUEST,
});
}, []);
useEffect(() => {
function onScroll() {
if (window.scrollY + document.documentElement.clientHeight > document.documentElement.scrollHeight - 300) {
if (hasMorePosts && !loadPostsLoading) {
dispatch({
type: LOAD_POSTS_REQUEST,
});
}
}
}
window.addEventListener('scroll', onScroll);
return () => {
window.removeEventListener('scroll', onScroll);
};
}, [ hasMorePosts, loadPostsLoading, mainPosts]);
return (
<AppLayout>
{me && <PostForm />}
{mainPosts.map((post) => <PostCard key={post.id} post={post} />)}
</AppLayout>
);
};
export default Home;
sagas/post.js
import { all, fork, put, takeLatest, delay, throttle, call } from 'redux-saga/effects';
import axios from 'axios';
import {
LOAD_POSTS_REQUEST,
LOAD_POSTS_SUCCESS,
LOAD_POSTS_FAILURE,
ADD_POST_REQUEST,
ADD_POST_SUCCESS,
ADD_POST_FAILURE,
ADD_COMMENT_REQUEST,
ADD_COMMENT_SUCCESS,
ADD_COMMENT_FAILURE,
REMOVE_POST_REQUEST,
REMOVE_POST_SUCCESS,
REMOVE_POST_FAILURE,
} from '../reducers/post';
import {
ADD_POST_TO_ME,
REMOVE_POST_OF_ME,
} from '../reducers/user';
function addCommentAPI(data) {
return axios.post(`/post/${data.postId}/comment`, data); // POST /post/1/comment
};
function* addComment(action) {
try {
const result = yield call(addCommentAPI, action.data);
yield put({
type: ADD_COMMENT_SUCCESS,
data: result.data,
});
} catch (err) {
yield put({ // put => dispatch 다.
type: ADD_COMMENT_FAILURE,
data: err.response.data,
});
};
};
function loadPostsAPI(data) {
return axios.get('/posts', data);
};
function* loadPosts(action) {
try {
const result = yield call(loadPostsAPI, action.data);
yield put({
type: LOAD_POSTS_SUCCESS,
data: result.data,
});
} catch (err) {
console.error(err);
yield put({ // put => dispatch 다.
type: LOAD_POSTS_FAILURE,
data: err.response.data,
});
}
}
function addPostAPI(data) {
return axios.post('/post', { content: data });
};
function* addPost(action) {
try {
const result = yield call(addPostAPI, action.data);
yield put({
type: ADD_POST_SUCCESS,
// data: action.data,
data: result.data
});
yield put({
type: ADD_POST_TO_ME,
data: result.data.id,
});
} catch (err) {
console.error(err);
yield put({
type: ADD_POST_FAILURE,
data: err.response.data,
});
};
};
function removePostAPI(data) {
return axios.delete(`/api/post/${data.postId}/comment`, data);
};
function* removePost(action) {
try {
// const result = yield call(removePostAPI);
yield delay(1000);
yield put({
type: REMOVE_POST_SUCCESS,
data: action.data,
});
console.log('removePost');
yield put({
type: REMOVE_POST_OF_ME,
data: action.data,
});
} catch (err) {
console.error(err);
yield put({
type: REMOVE_POST_FAILURE,
data: err.response.data,
});
};
};
function* watchLoadPosts() {
yield throttle(5000, LOAD_POSTS_REQUEST, loadPosts);
};
function* watchAddPost() {
yield takeLatest(ADD_POST_REQUEST, addPost);
};
function* watchAddComment() {
yield takeLatest(ADD_COMMENT_REQUEST, addComment);
};
function* watchRemovePost() {
yield takeLatest(REMOVE_POST_REQUEST, removePost);
};
export default function* postSaga() {
yield all([
fork(watchAddPost),
fork(watchLoadPosts),
fork(watchRemovePost),
fork(watchAddComment),
]);
};
BACK
routes/posts.js
const express = require('express');
const { Post, User, Image, Comment } = require('../models/');
const router = express.Router();
router.get('/', async (req, res, next) => { // GET /posts
try {
const posts = await Post.findAll({
limit: 10,
order: [['createdAt', 'DESC']],
inculude: [{
model: User,
attributes: ['id','nickname'],
}, {
model: Image,
}, {
model: Comment,
include: [{
model: User,
attributes: ['id','nickname'],
}],
}],
});
res.status(200).json(posts);
} catch (error) {
console.log(error);
next(error);
}
});
module.exports = router;
로그인 창도 안뜨고 에러가 떳었는데.
include 를 모두 해주니 정상적으로 로그인도 되고 게시글도 등록됩니다.
하지만 등록후 바로 다시 위와 똑같은 에러가 동일하게 뜹니다.
PostCard 에 key 관련 에러로 추측됩니다.
BACK
routes/posts.js
답변을 작성해보세요.
0
castinglife
질문자2020.08.05
헤멘 부분을 정리해서 올려 봅니다.
DB 에서 게시글 불러오기, DB에서 게시글 추가 부분에서 에러 메세지를 이해하는 부분이 부족해서 많이 헤멧네요~
routes/post.js
const express = require('express');
const { Post, Image, Comment, User } = require('../models');
const { isLoggedIn, } = require('./middlewares');
const router = express.Router();
router.post('/', isLoggedIn, async (req, res, next) => { // POST /post
try {
const post = await Post.create({
content: req.body.content,
UserId: req.user.id,
});
const fullPost = await Post.findOne({
where: { id: post.id },
include: [{
model: Image,
}, {
model: Comment,
include: [{
model: User, // 댓글 작성자
attributes: ['id', 'nickname'],
}],
}, {
model: User, // 게시글 작성자
attributes: ['id', 'nickname'],
}, {
model: User, // 좋아요 누른 사람
as: 'Likers',
attributes: ['id'],
}],
});
res.status(201).json(fullPost);
} catch (error) {
console.error(error);
next(error);
}
});
module.exports = router;
routes/posts.js
const express = require('express');
// const { Op } = require('sequelize');
const { Post, User, Image, Comment } = require('../models/');
const router = express.Router();
router.get('/', async (req, res, next) => { // GET /posts
try {
const posts = await Post.findAll({
limit: 10,
order: [['createdAt', 'DESC']],
// order: [
// ['createdAt', 'DESC'],
// [Comment, 'createdAt', 'DESC'],
// ],
include: [{
model: User,
attributes: ['id', 'nickname'],
}, {
model: Image,
}, {
model: Comment,
include: [{
model: User,
attributes: ['id', 'nickname'],
order: [['createdAt', 'DESC']],
}],
}, {
model: User, // 좋아요 누른 사람
as: 'Likers',
attributes: ['id'],
}, {
model: Post,
as: 'Retweet',
include: [{
model: User,
attributes: ['id', 'nickname'],
}, {
model: Image,
}]
}],
});
console.log(posts);
res.status(200).json(posts);
} catch (error) {
console.log(error);
next(error);
}
});
module.exports = router;
0
castinglife
질문자2020.08.05
모두 Posts.js 에 include 관련문제 였습니다.. ㅡ.ㅡ;; 휴~ 2일을 헤멘듯... 덕분에 back 돌아가는 패턴을 익히는데 조금 더 익숙해진느낌입니다.^^
0
조현영
지식공유자2020.08.04
0 of undefined면 뭐가 undefined인지부터 파악해보셔야 합니다. PostCard.js 38번째줄 정도라고 나와있네요. 에러메시지에 모든 게 다 있습니다. 이번에 올리실때도 PostCard를 제외한 다른 파일만 올리셨어요.
routes/posts.js의 get /에은 include 관련 오타가 있었고요. retweet include할때도 image include하는 거 빠뜨리셨습니다.
답변 3