수강이 제한됩니다.
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결React로 NodeBird SNS 만들기
_app.js에서 LOAD_USER_REQUEST 액션이 디스패치 되지 않아요
ctx 내에 store와 dispatch 다 있고 에러도 안나고 콘솔메세지도 찍히는데 리덕스 데브 툴즈에는 일단 액션 날라가는게 없고 회원 정보도 다시 안불러와서여 if(!state.user.me) { console.log("ctx : " , ctx); ctx.store.dispatch({ type: LOAD_USER_REQUEST, }); console.log("유저 정보 불러 오기"); } front/pages/_app.js 전체 코드 // front\pages\_app.js import React from 'react'; import Head from 'next/head'; import AppLayout from '../components/AppLayout'; import withRedux from 'next-redux-wrapper'; import reducer from '../reducers'; import { Provider } from 'react-redux'; import createSagaMiddleware from 'redux-saga'; import rootSaga from '../sagas'; import { applyMiddleware, compose, createStore } from 'redux'; import PropTypes from 'prop-types'; import withReduxSaga from 'next-redux-saga'; import { LOAD_USER_REQUEST } from '../reducers/user'; import axios from 'axios'; const NodeBird = ({ Component, store, pageProps }) => { return ( <Provider store={store}> <Head> <title>NodeBird</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/antd/3.20.5/antd.css" /> <link rel="stylesheet" type="text/css" charSet="UTF-8" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css" /> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css" /> </Head> <AppLayout> <Component {...pageProps} /> </AppLayout> </Provider> ) } NodeBird.propTypes = { Component: PropTypes.elementType.isRequired, store: PropTypes.object.isRequired, pageProps: PropTypes.object.isRequired, }; NodeBird.getInitialProps = async (context) => { // console.log(context); const { ctx, Component } = context; let pageProps = {} const state = ctx.store.getState(); const cookie = ctx.isServer ? ctx.req.headers.cookie : ''; axios.defaults.headers.Cookie = ''; if (ctx.isServer && cookie) { axios.defaults.headers.Cookie = cookie; } if(!state.user.me) { console.log("ctx : " , ctx); ctx.store.dispatch({ type: LOAD_USER_REQUEST, }); console.log("유저 정보 불러 오기2"); } if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) || {}; } // console.log("pageProps : " , pageProps); return { pageProps }; }; const configureStore = (initialState, options) => { const sagaMiddleware = createSagaMiddleware(); const middlewares = [sagaMiddleware]; const enhancer = process.env.NODE_ENV === 'production' ? compose(applyMiddleware(...middlewares)) : compose( applyMiddleware(...middlewares), !options.isServer && typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined' ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f, ); const store = createStore(reducer, initialState, enhancer); // sagaMiddleware.run(rootSaga); store.sagaTask = sagaMiddleware.run(rootSaga); return store; }; export default withRedux(configureStore)(withReduxSaga(NodeBird));
- 미해결React로 NodeBird SNS 만들기
한가지 궁금한게 있습니다!
새로고침시 로그아웃되거나, 로그인 유지와 관련되서는 서버사이드 렌더링때 다루시는 것 같은데, 혹시, 한가지 예로, 특정 사용자가 권한을 부여받길 기다리거나, 인증에대해 기다리는 사용자가 로그인 할 경우, 서비스를 이용할 수 없도록 특정 페이지로 강제로 이동시켜주거나, 서비스 이용 불가능 상태로 만들어주고 싶은데, (모든 페이지 이동을 시도할 경우, 무조건 인증 대기를 위한 특정 페이지로만 강제 이동) 혹시 이부분도 서버사이드 렌더링과 관련이 있을까요..? 모든 페이지에서 사용자 권한에 대한 체크기능을 넣지않고, 필터와 같이 방법이 있을껏 같은데, 서버사이드 렌더링에서 다루시는 부분으로 응용가능한부분일까요? 아니라면, 간략한 기술명이나, 이름 힌트좀 알려주실수 있을까요..?
- 미해결React로 NodeBird SNS 만들기
게시글 존재 findone 중복제거
안녕하세요~ 게시글 존재 검사 중복로직을 제거해보려고 시도를 해보았습니다. 포스트 존재 확인후 조회한 post객체를 다시 router.post('/:id/like'.. 의 async(req,res,next)=>{} 함수로 넘겨주려고 했으나 방법을 못찾아 async(req,res,next)함수를 감싸는 방식으로 하였습니다. router.post('/:id/like', isLoggedIn, isPost, asycn(req,res,next,post)) ->이런 방식으로 할 수 있는 방법이 있나요? isLoggedin 미들웨어 는 단순히 next()로 다음 미들웨어로 넘기는 거라 하셔서 조회된 post 값을 어떻게 다음 미들웨어로 넘기는지 궁금합니다. //middleware.jsconst db = require( '../models' );exports.isPost = asyncFunc => { return (async (req, res, next) => { try { const post = await db.Post.findOne( { where: { id: req.params.id }, } ); if ( !post ){ return res.status( 404 ).send( '게시글이 존재하지 않습니다.' ); }else{ return await asyncFunc( req, res, next, post ); } } catch (e) { console.error(e); return next( e ); } });};//post.jsrouter.post( '/:id/like', isLoggedIn, isPost( async (req, res, next, post) => { try { console.log( 'post',post ); await post.addLiker( req.user.id ); res.json( { userId: req.user.id } ); } catch (e) { console.error( e ); next( e ); }} ) );
- 미해결React로 NodeBird SNS 만들기
에러질문드려요
dispatch 사용시 해당에러가 나옵니다 npm에서 설치하신것들은 따라서 설치를 하고 코드도 똑같이 작성했는데 에러가 나옵니다 해결방법 문의드립니다
- 미해결React로 NodeBird SNS 만들기
질문이요
리듀서에서 initialState 안에 me 를 null 값을 해놨어요. 그리고 로그인 성공시, me 에 유저정보가 들어가잖아요. 그런데 왜, 새로고침을 하면 me 는 null 상태로 돌아 가는걸까요? 똑같은 예시로, initialState 안에 hi라는 state 안에 "hello" 라는 스트링값으로 초기화를 해주었어요. 그리고 로그인 성공시, hi 라는 state안에 "world"라는 스트링 값으로 변경을 해주었어요. 그리고, AppLayout.js 에서 useSelector를 통해서, hi state값을 갖고옵니다. 로그인시에는, "world" 라는 값을 갖고 오지만 새로고침시에는 console.log 찍으면 innitialState 값인 "hello"가 나오네요. 새로고침을 하면, innitialState 값이 나올까요? 그냥 리액트 특성인가요 ??
- 미해결React로 NodeBird SNS 만들기
sudo 계정이후 permission denied
안녕하세요 영상 보고 첫 배포 성공 후, 똑같은 코드를 깃허브에서 다시 다운받아서 다시 배포하는 연습을 하고 있습니다. front 서버에 배포를 하려고 하는데 - sudo su - npm run build ( build 디렉토리는 /home/ubuntu/새로정의한프로젝트명/front) 여기서 permission denied가 떨어지네요 이하 에러 로그입니다.=------------------------------------------------> root@ip-172-31-35-199:/home/ubuntu/zepettoland/ch9_zepettoland/front# npm run build > react-nodebird-front@1.0.0 build /home/ubuntu/zepettoland/ch9_zepettoland/front > cross-env ANALYZE=true next build sh: 1: cross-env: Permission denied npm ERR! code ELIFECYCLE npm ERR! errno 126 npm ERR! react-nodebird-front@1.0.0 build: `cross-env ANALYZE=true next build` npm ERR! Exit status 126 npm ERR! npm ERR! Failed at the react-nodebird-front@1.0.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /root/.npm/_logs/2019-11-25T03_23_39_728Z-debug.log 기존 소스에 프로젝트명만 바꾼건데요 문의드리겠습니다. 감사합니다.
- 미해결React로 NodeBird SNS 만들기
라우터의 addLiker 함수는 어떻게 사용하는건가여?
addLiker 함수는 이름이 어떻게 정해지는건가여? 모델에서 db.Post.belongsToMany(db.User, { through: 'Like', as: 'Likers' }); 이렇게 정의하고 라우터에서 await post.addLiker(req.user.id); 이렇게 하면 좋아요가 추가 되는거 같은데 as가 Likers 인데 함수는 addLiker라서여 s는 시퀄라이즈에서 알아서 붙여주는건가여?
- 미해결React로 NodeBird SNS 만들기
질문이여
리덕스사가를 통해서, 회원가입 액션을 백엔드로 보냈어요. 현재, 같은 아이디가 있을때, 백엔드에서 같은 아이디가 있다고 에러를 보내주는걸 구현 하고 있는데요. 백엔드/ routes if(exUser){ return res.status(403).send({error:'같은아이디있음'}); } 이런식으로, error 라는 객체안에 "같은아이디 있음 "을 saga 에서 다시 받고 싶어요 .. front/saga function* signUp(action){ try { yield call(signUpAPI,action.data); yield put(sign_Up_Success_Action()); } catch (e) { console.error(e); yield put(sign_Up_Fail_Action(e.error)); } } 이런식으로 받으려고 하는데, error라는 객체는 안오고, 그냥 진짜 에러가 console.log 가 찍히네요,, POST http://localhost:3075/user/signUp 403 (Forbidden) 그런데 또 network 에서 보면은 , preview 에는 {error: "A userId already exits"} error: "A userId already exits" 이렇게 정상적으로 찍히는데, 무엇이 문제인가요... 지금 이게 ,return res.status(403).send({error:'같은아이디있음'}); 프론트 엔드로 보내는게 맞지않나요?? 서로 로컬 서버가 달라서 못 받는걸까요/? 그래서, saga쪽에서는 진짜 error 가 낫으니, error를 표현을 해주는걸까요?? 어떻게 동작하는지 잘 모르겠네요...
- 미해결React로 NodeBird SNS 만들기
NodeBird 컴포넌트에서
NodeBird 컴포넌트를 next의 Container 컴포넌트로 감싸셨는데, Container는 어떤 역할을 하는건가요? 공식 문서에는 딱히 언급이 없고, 검색 결과도 나오지 않아서.. 여쭤봅니다.
- 해결됨React로 NodeBird SNS 만들기
질문이여
리덕스 사가에서여, function* signUp(action){ try{ yield call(signUpAPI, action.data); yield put({ type: SIGN_UP_SUCCESS }) }catch(e){ yield put({ type:SIGN_UP_FAILURE, error:e, }) } } 이 부분이요 ,, 제가 , export const signUpAction = () =>{ return type: SIGN_UP_SUCCESS } 이거를 다른 파일에서 뽑아서, function* signUp(action){ try{ yield call(signUpAPI, action.data); yield put(signUpAction()) // <-에러 }catch(e){ .... } yield put(signUpAction()) 이 부분에서 이런 에러가 나더라구요. actions must be plain objects. use custom middleware for async actions 인터넷에 찾아보니까 thunk? 인가를 쓰라고 하던데, 왜 그런거죠... 잘 이해가 안가네요? signUpAction 함수가 비동기가 아니여서 그런건가요 ??
- 미해결React로 NodeBird SNS 만들기
useRef 대신에
useRef 대신에 state에서 배열을 선언해서 해결해주어도 무방한가요?
- 미해결React로 NodeBird SNS 만들기
useEffect에서 함수를 반환하면
useEffect에서 함수를 반환하면 그 함수를 컴포넌트가 마운트 되기 이전에 실행해주는 게 맞나요?
- 미해결React로 NodeBird SNS 만들기
회원가입 완료 후 질문입니다!
안녕하세요! 강의 정말 잘 보고 있습니다. 회원가입 후 등록까지 정상적으로 완료했는데요! dispatch 후 back 서버에서 성공이라면 성공 메시지와 응답메세지, 실패라면 실패 메시지와 응답메세지 + 오류 코드 이렇게 받을텐데요. 받은 메시지에 따라 사용자에게 보여줄려면 보통 어떻게 처리해야 하나요? next를 사용한 강의에서는 dispatch ~~ ).then 구문을 사용하지 않다보니, useSelector을 통해 ErrorReason 값이 '' -> "~~" 식의 변화가 생긴다면 useEffect로 해당 state 변화 감지 후, if로 alert 하여 디피하는 방법을 사용하면될지.. 성공일때도 성공은 한가지 경우로 명확하니까, 액션을 통해 특정 succes state는 true 변경해줄테니, useSelector 를 통해, success 명의 state를 감지하여, useEffect 로 alert 후 Router.push 를 해준다거나.. (예: 로그인 할경우 > "~님 환영합니다" alert 후, 특정 페이지로 짠~ 실제 실무 코드에서는 해당 처리를 어떻게 해주는지 궁금합니다. 해당 기능만 미리 알고 싶에서 8강의 소스만 미리 살짝 분석해보니, 비슷한 처리는 없어보여서요..ㅠㅠ
- 미해결React로 NodeBird SNS 만들기
next를 사용하면,
next를 사용하면 기본적으로는 서버사이드 렌더링을 하는 것이 맞는지 궁금합니다. 기본 리액트 앱의 소스보기를 누르면 소스 보기에 내용 부분에 아무것도 나오지 않는 반면에, next로 만든 리액트 앱은 비동기로 불러와야 할 데이터를 빼면 태그들이 다 나오는 것 때문에 궁금합니다. - next는 기본적으로 ssr을 하는데, getinitialprops으로 조금 더 빨리 데이터를 붙여줄 수 있는 것인가요 - 아니면 getinitialprops을 사용함으로써 ssr을 할 수 있게 되는 것인가요?
- 미해결React로 NodeBird SNS 만들기
테이블 생성 시 첫 글자가 대문자로 됩니다...
안녕하세요~^^ 제로초님이랑은 다르게 테이블 생성 시 첫 글자가 대문자로 됩니다...참고로 맥 OS이고 MySQL 버전은 5.7.13입니다.
- 미해결React로 NodeBird SNS 만들기
db.sequelize.sync()가 동작을 안합니다...ㅜㅜ;
안녕하세요~강의 재밌게 잘 보고 있습니다~^^ DB 접속 시도를 하니 아래처럼 에러가 발생하는데 원인을 잘 모르겠네요...도움 좀 받을 수 있을까요~??
- 미해결React로 NodeBird SNS 만들기
댓글 입력후에 key 에러가 발생해요
안녕하세요 댓글 달고 나서 키에러가 발생하는데 pages/index.js에서 key를 c.id 로 바꿔도 에러가 발생해여 어떻게 수정해야 되는지 알려주시면 감사여 https://stackoverflow.com/questions/58908628/i-got-a-key-error-after-entering-a-comment-i-dont-know-how-to-fix-react-propb/58908862#58908862
- 미해결React로 NodeBird SNS 만들기
더미데이터를 갖고오지못하는것 같습니다...!
//UserProfile.jsx import React, { useCallback } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Card, Button, Avatar } from 'antd'; import { logoutAction } from '../reducers/user'; const UserProfile = () => { const { user } = useSelector(state => state.user); const dispatch = useDispatch(); console.log(user); const onLogout = useCallback(() => { dispatch(logoutAction); }, []); return ( <div> <Card actions= {[ <div key='twit'> 짹짹 <br/> {user.Posts.length} </div>, <div key='twit'> 팔로잉 <br/> {user.Followings.length} </div>, <div key='twit'> 팔로워 <br/> {user.Followers.length} </div>, ]} > <Card.Meta avatar = {<Avatar>{user.nickname[0]}</Avatar>} title = {user.nickname} /> </Card> <Button onClick={onLogout}>로그아웃</Button> </div> ); } export default UserProfile; //reducers/user.js export const initialState = { isLoggedIn: false, user: null, signUpData: {}, loginData: {}, }; const dummyUser = { nickname: '지나', Posts: [], Followings: [], Followers: [], isLoggedIn : true, signUpData : {}, } const LOG_IN = 'LOG_IN'; //액션의 이름 const LOG_OUT = 'LOG_OUT'; const SIGN_UP = 'SIGN_UP'; //동적 데이터(값이 계속 바뀜) 경우 action을 함수로 만들어야 export const signUpAction = (data) => { return { type: SIGN_UP, data, } } export const loginAction = { type: LOG_IN, } export const logoutAction = { type: LOG_OUT, } const reducer = (state = initialState, action) => { switch (action.type) { case LOG_IN: { return { ...state, isLoggedIn: true, user: dummyUser, loginData: action.data, } } case LOG_OUT: { return { ...state, isLoggedIn: false, user: null, } } case SIGN_UP: { return { ...state, signUpData: action.data, } } default: { return { ...state, } } } } export default reducer; 이렇게 되어있는데 console.log(user); 값이 null 로 뜹니다ㅠㅠ 그래서 뒤에 {user.Posts.length} 와 같은 부분들이 다 안불러와지는것 같아요ㅠㅠ 제로초님 깃헙도 살펴봤는데 뭐가 문제인지 안보이네요ㅠㅠㅠ
- 미해결React로 NodeBird SNS 만들기
댓글 입력할때 타입 에러가 발생해요
reducer code case ADD_COMMENT_SUCCESS: { const postIndex = state.mainPosts.findIndex(v => v.id === action.data.postId); const post = state.mainPosts[postIndex]; const Comments = [...post.Comments, action.data.comment]; const mainPosts = [...state.mainPosts]; mainPosts[postIndex] = { ...post, Comments }; return { ...state, isAddingComment: false, mainPosts, commentAdded: true, }; } const Comments = [...post.Comments, action.data.comment]; git: https://github.com/hyunsokstar/node_bird_33 https://github.com/hyunsokstar/node_bird_33/blob/master/front/reducers/post.js https://github.com/hyunsokstar/node_bird_33/blob/master/front/components/PostCard.js에러가 발생하는 이유를 몰겠어요 const postIndex = state.mainPosts.findIndex(v => v.id === action.data.postId); 에 아이디가 없나 해서 찾아봤는데 그것도 아닌거 같아요
- 미해결React로 NodeBird SNS 만들기
질문이여
스타일드 컴포넌트 궁금한게 있는데여, 자식 js 파일에 있는 임의로 만들어진 컴포넌트는요, 부모js 파일에서 overwriting 이 불가능한건가여?? 예를들어서, index.js ((부모)와 login.js(자식) 가 있다고 가정할때요. login.js 에는 그림한개, Id, pw 용 입력창, 그리고 로그인 버튼이 있습니다. export const Overlay = styled.div` border: 10px inset blue; ` <Overlay> 그림한개 </Overlay> 그림 한개에 적용을 시켜주었다고 가정하구요. index.js 에서 (login.js 의 부모) login {Overlay} from login.js const Overwriting = styled.div` > Overlay { margin: 0px 0px 10px 10px; } ` <Overwriting> <login/> </Overwriting> 이런식으로 오버라이팅은 불가능한가요??