inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[리뉴얼] React로 NodeBird SNS 만들기

로그아웃 -> 마이페이지 properties of null 에러 발생

264

가도로이

작성한 질문수 5

0

안녕하세요 제로초님 !
로그인 상태가 false일 경우, '마이페이지'가 보이도록, 반대일 경우엔 '로그인'이 보이도록 페이지를 만들었습니다.
문제는 마이페이지(유저프로필)에서 로그아웃 버튼을 누르면 user가 정상적으로 null값으로 바뀌는데
 
 
 
여기서 왜 Posts 속성이 없다는 에러가 발생하는지 모르겠습니다..
로그아웃을 하는데 왜 마이페이지 에러가 발생하는걸까요 ㅠㅠ..
 
 
//components/AppLayout.js
 
import React from "react";
import PropTypes from "prop-types";
import Link from "next/link";
import { Row, Col } from "antd";
import styles from '../styles/styles.module.css';
import { useSelector } from 'react-redux';

const AppLayout = ({ children }) => {
  const {logInDone} = useSelector((state) => state.user);

  return (
    <>
      <Link href="/">
        <a><h1 className={styles.logo}>놀멍쉬멍
          <img src="logoIcon.png" alt="logoImage" style={{width: '24px'}} /></h1>
        </a>
      </Link>
        <div>{children}</div>
      <Row className={styles.bottomNav}>
        <Col xs={4}><Link href="/writePost"><a>새글작성</a></Link></Col>
        <Col xs={4}><Link href="/community"><a>커뮤니티</a></Link></Col>
        <Col xs={8}>
          <Link href="/">
            <a><img className={styles.centerNav} src='../icon.png'/></a>
          </Link>
        </Col>
        <Col xs={4}><Link href="/findPlace"><a>장소검색</a></Link></Col>
        {logInDone 
        ? <Col xs={4}><Link href="/mypage"><a>마이페이지</a></Link></Col>
        : <Col xs={4}><Link href="/login"><a>로그인</a></Link></Col>}
      </Row>
    </>
  );
};

AppLayout.propTypes = {
  children: PropTypes.node.isRequired,
};

export default AppLayout;
 
 
//pages/login.js
 
import React from "react";
import AppLayout from "../components/AppLayout";
import Head from 'next/head';
import MyPage from '../components/MyPage';
import LoginForm from '../components/LoginForm';
import { useSelector } from 'react-redux';

const login = () => {
  const {logInDone} = useSelector((state) => state.user);
  return (
    <>
      <Head>
          <meta charSet="utf-8" />
          <title>로그인 | 놀멍쉬멍</title>
      </Head>
      <AppLayout>
      { logInDone ? <MyPage /> : <LoginForm />}
      </AppLayout>
    </>
  );
};

export default login;
 
 
//pages/myPage.js
 
import React from 'react';
import AppLayout from '../components/AppLayout';
import Head from 'next/head';
import MyPage from '../components/MyPage';
import LoginForm from '../components/LoginForm';
import { useSelector } from 'react-redux';

const myPage = () => {
    const {logInDone} = useSelector((state) => state.user);
    return (
        <>
            <Head>
                <meta charSet="utf-8" />
                <title>마이페이지 | 놀멍쉬멍</title>
            </Head>
            <AppLayout>
                { logInDone ? <MyPage /> : <LoginForm />}
            </AppLayout>
        </>
    );
};

export default myPage;

 

//components/LoginForm.js

 

import React, { useCallback, useEffect } from 'react';
import {Form, Input, Button} from 'antd';
import Link from 'next/link';
import styles from '../styles/login.module.css';
import styled from 'styled-components';
import useInput from '../hooks/useInput';
import { useDispatch, useSelector } from 'react-redux';
import {loginRequestAction} from '../reducers/user';

const LoginBtn = styled(Button)`
    background-color: white;
    border: 1px solid #857171;
    max-width: 600px;
    margin: 20px 0;
    width: 100%;
    margin-bottom: 40px;
    height: 40px;

    &:hover {
        background-color: #857171;
        border: 1px solid #857171;
        color: white;
    }
`;

const LoginInput = styled(Input)`
    height: 40px;
`;

const LoginForm = () => {
    const dispatch = useDispatch();
    const {logInLoading} = useSelector((state) => state.user);
    const [email, onChangeEmail] = useInput('');
    const [password, onChangePassword] = useInput('');

    const onSubmitBtn = useCallback(() => {
        console.log(email, password);
        dispatch(loginRequestAction({email, password}));
    }, [email, password]);

    return (
        <>
        <Form className={styles.loginForm} onFinish={onSubmitBtn}>
            <div className={styles.inputWrapper}>
                <label htmlFor="user-email">이메일</label>
                <br />
                <LoginInput name="user-email" type="email" value={email} onChange={onChangeEmail} required/>
            </div>
            <div className={styles.inputWrapper}>
                <label htmlFor="user-password">비밀번호</label>
                <br />
                <LoginInput 
                    name="user-password" 
                    type="password" 
                    value={password} 
                    onChange={onChangePassword} 
                    required
                />
            </div>
            <div className={styles.buttonWrapper}>
                <LoginBtn htmlType="submit" loading={logInLoading}>로그인</LoginBtn>
                < br/>
                <span>놀멍쉬멍이 처음이신가요?</span>
                <Link href="/signup"><a>회원가입</a></Link>
            </div>
        </Form>
        </>
    );
};

export default LoginForm;

 

//components/MyPage.js

 

import React, { useCallback } from 'react';
import {Card, Avatar, Button} from 'antd';
import FollowList from './FollowList';
import styled from 'styled-components';
import page from '../styles/wrapper.module.css';
import { useDispatch, useSelector } from 'react-redux';
import {logoutRequestAction} from '../reducers/user';

    const LogoutBtnWrapper = styled.div`
        display: flex;
        justify-content: flex-end;

        button {
            border: none;
            background-color: transparent;
            color: gray;
        }
    `;

const MyPage = () => {
    const dispatch = useDispatch();
    const {logOutLoading, user} = useSelector((state) => state.user);

    const onLogout = useCallback(() => {
        dispatch(logoutRequestAction());
    }, []);

    return ( 
        <div className={page.pageWrapper}>
        <div>
            <Card
            cover={
            <img
                alt="my_profile_pic"
                src="../cute.jpeg"
            />}
            actions={[
                        <div key="writedPost">작성한 글<br />{user.Posts.length}</div>,
                        <div key="followings">팔로잉<br />{user.Followings.length}</div>,
                        <div key="followers">팔로우<br />{user.Followers.length}</div>
                    ]}
                    >
                    <Card.Meta
                        avatar={<Avatar>{user.nickname[0]}</Avatar>}
                        title={user.nickname}
                        description="개냥이 키웁니다 우하하"
                        />
                    <br />
                    <LogoutBtnWrapper>
                        <Button onClick={onLogout} loading={logOutLoading}>로그아웃</Button>
                    </LogoutBtnWrapper>
                </Card>
        </div>
        <div>
            <div style={{margin: '20px 0'}}>
                <FollowList header="나를 팔로잉하는 사람" data={user.Followings}/>
                <FollowList header="내가 팔로우하는 사람" data={user.Followers}/>
            </div>
        </div>
        </div>
    );
};

export default MyPage;

 

 

redux react express nodejs Next.js

답변 1

0

제로초(조현영)

코드를 잘 살펴보시면 당연히 에러가 날수밖에 없습니다. 로그아웃을 했는데 마이페이지를 렌더링하려니 에러가 나는 것이죠. user가 null인데 user.Posts가 말이 안 되죠. 제 강좌 프로필 페이지 소스코드에서 어떻게했나 확인해보세요.

넥스트 버젼 질문

0

90

2

로그인시 401 Unauthorized 오류가 뜹니다

0

104

1

무한 스크롤 중 스크롤 튐 현상

0

192

1

특정 페이지 접근을 막고 싶을 때

0

116

2

createGlobalStyle의 위치와 영향범위

0

102

2

인라인 스타일 리렌더링 관련

0

97

2

vsc 에서 npm init 설치시 오류

0

157

2

nextjs 15버전 사용 가능할까요?

0

166

1

화면 새로고침 문의

0

129

1

RTK에서 draft, state 차이가 있나요?

0

160

2

Next 14 사용해도 될까요?

0

455

1

next, node 버전 / 폴더 구조 질문 드립니다.

0

359

1

url 오류 질문있습니다

0

214

1

ssh xxxxx로 우분투에 들어가려니까 port 22: Connection timed out

0

391

1

sudo certbot --nginx 에러

0

1293

2

Minified React error 콘솔에러 (hydrate)

0

477

1

카카오 공유했을 때 이전에 작성했던 글이 나오는 버그

0

255

1

프론트서버 배포 후 EADDRINUSE에러 발생

0

337

1

npm run build 에러

0

525

1

front 서버 npm run build 중에 발생한 에러들

0

399

1

서버 실행하고 브라우저로 들어갔을때 404에러

0

350

2

css 서버사이드 랜더링이 적용되지 않아서 문의 드립니다.

0

290

1

팔로워 3명씩 불러오고 데이터 합쳐주는걸로 바꾸고 서버요청을 무한으로하고있습니다.

0

249

2

해시태그 검색에서 throttle에 관해 질문있습니다.

0

206

1