강의

멘토링

커뮤니티

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

hm_stom님의 프로필 이미지
hm_stom

작성한 질문수

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

제로초님 질문있습니다

해결된 질문

작성

·

253

0

현재 개인프로젝트 진행중인데

강이보면 getServerSideProrps를 index에 적어서 로그인유지와 게시물을 미리 가져오는 방식으로 구현하셨습니다

하지만 저의 프로젝트는 index.js에서는 map()으로 게시글을 뿌려주는 곳이 아니라  로그인 유지만 가능하게 해놨는데

index.js가아닌 다른 컴포넌트 쪽에서 게시글을 map으로 뿌려주고있습니다. 하지만 메인페이지에서는 렌더링 되어야하구요

이런경우에는 serversideprorps를 어떻게 적용해야할까요 ? 여러번 사용할 수 있나요 ?

답변 2

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

무슨 말씀이신지 잘 모르겠습니다.

index.js에서 getServerSideProps로 데이터를 가져오면 모든 컴포넌트에서 다 그 데이터를 사용할 수 있을 텐데요?

hm_stom님의 프로필 이미지
hm_stom
질문자

답변 감사합니다

제가 실수를 한 부분이 있었습니다 !!

0

hm_stom님의 프로필 이미지
hm_stom
질문자

index.js 의 내용입니다
import axios from 'axios';
import Head from 'next/head';
import React, { useEffect } from 'react';
import { END } from 'redux-saga';
import MainSection from '../components/MainSection';
import {
LOAD_PRODUCT_TYPE_REQUEST,
LOAD_USER_INFO_REQUEST,
} from '../reducers/action';
import wrapper from '../store/configureStore';

const index = () => {
console.log('index 페이지 들어옴');

// useEffect(() => {
// localStorage.getItem('vintage-info-user');
// }, []);

return (
<>
<Head>
<title>폴로딩고</title>
</Head>
{/* 섹션 */}
<MainSection />
{/* 상품페이지 */}
</>
);
};

export const getServerSideProps = wrapper.getServerSideProps(
async (context) => {
// index js의 리듀서 구조를 바꿔야함 중첩되게 끔

axios.defaults.headers.Cookie = '';

// 로그인을 공유하는 상황을 막기 위해서
const cookie = context.req ? context.req.headers.cookie : '';

// console.log('쿠키 : ', cookie);
// defaults 쿠기 설정 (로그인 했을 경우에만)
if (context.req && cookie) {
axios.defaults.headers.Cookie = cookie;
}

context.store.dispatch({
type: LOAD_USER_INFO_REQUEST,
});

// 첫 파에지 랜딩에는 최근 등록된 상품 기준으로 보여주거나 업로드 날짜가 가장 최근인 애들을 보여줘야함
context.store.dispatch({
type: LOAD_PRODUCT_TYPE_REQUEST,
data: 'all',
});

// 위에 REQUEST가 SUCCESS로 바뀔 때 까지 기다려주는 장치임
// 공식문서에 나옴
context.store.dispatch(END);
await context.store.sagaTask.toPromise(); // store.sagatask에서 등록해놓음(index.js에서)
/// /////////////////////////////////////////////////
}
);
export default index;
//////////////////////////////
MainSection.js내용입니다.
import React, { useEffect, useRef } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/dist/ScrollTrigger';
import { useDispatch } from 'react-redux';
import { SectionOne, SectionTwo, SectionThree } from '../style/SectionStyle';
import Product from './Product';
import { ProductStyle } from '../style/ProductStyle';
import { addPost } from '../reducers/product/productAction';

// register ScrollTrigger
gsap.registerPlugin(ScrollTrigger);

const MainSection = () => {
const dispatch = useDispatch();

const refSlide1 = useRef(null);
const refSlide2 = useRef(null);
const refSlide3 = useRef(null);

const revealRef1 = useRef(null);

const onClick = () => {
dispatch(addPost);
};
useEffect(() => {
// 임시, 확인후 삭제 => 인증키가 없어서 401뜨면 cors 문제 해결된거 맞음
// axios.get('2/tweets/search/recent').then(function (response) {
// console.log('응답결과', response);
// });
// const sections = [refSlide1, refSlide2, refSlide3].map(
// (ref) => ref.current
// );
// const triggers = sections.map((panel) => {
// return ScrollTrigger.create({
// trigger: panel,
// start: "top top",
// end: "+=50%",
// pin: true,
// scrub: 3,
// pinSpacing: true,
// })
// })
// const snap = ScrollTrigger.create({
// snap: 1 / (sections.length - 1),
// })
// return function cleanup() {
// triggers.map((trigger) => trigger.kill())
// snap.kill()
// }
}, []);

useEffect(() => {
const texts = [revealRef1].map((ref) => ref.current);
gsap.from(refSlide1.current, {
duration: 1,
autoAlpha: 0,
ease: 'none',
delay: 0.1,
});
texts.forEach((el) => {
gsap.fromTo(
el,
{
autoAlpha: 0,
},
{
duration: 1,
autoAlpha: 1,
ease: 'none',
scrollTrigger: {
trigger: el,
start: 'top center+=100',
toggleActions: 'play none none reverse',
},
}
);
});
}, []);

return (
<>
<SectionOne ref={refSlide1}>
<div className="section__image section__image--a" />
<div className="showcase_contents">
<h1>90% SALE</h1>
<span>세일 기간 중 교환 및 반품이 불가능합니다.</span>
</div>
</SectionOne>

<SectionTwo ref={refSlide2}>
<div className="showcase_contents" ref={revealRef1}>
<ul className="main_banner_lists">
<li>
<a href="#">
<img src="images/main-banner-top-1.jpg" />
</a>
<p className="title">
<span>TIE_DYE_TSHIRT</span>
</p>
<p className="summary">다양한 타이다이 티셔츠</p>
</li>
<li>
<a href="#">
<img src="images/main-banner-top-2.jpg" />
</a>
<p className="title">
<span>HAWAIAN SHIRT</span>
</p>
<p className="summary">하와이안 셔츠</p>
</li>
<li>
<a href="#">
<img src="images/main-banner-top-3.jpg" />
</a>
<p className="title">
<span>SWEATSHIRT</span>
</p>
<p className="summary">스타일리쉬 트렌치 코트</p>
</li>
<li>
<a href="#">
<img src="images/main-banner-1.jpg" />
</a>
<p className="title">
<span>NEW CUSTOMERS</span>
</p>
<p className="summary">신규회원 5% 할인 쿠폰 발급!</p>
</li>
<li>
<a href="#">
<img src="images/main-banner-2.jpg" />
</a>
<p className="title">
<span>MEMBER LEVEL</span>
</p>
<p className="summary">빈티지톡 회원등급 안내</p>
</li>
<li>
<a href="#">
<img src="images/main-banner-3.jpg" />
</a>
<p className="title">
<span>CONSIGNMENT SALES</span>
</p>
<p className="summary">위탁판매 안내</p>
</li>
</ul>
</div>
</SectionTwo>

<SectionThree>
<div className="container" ref={refSlide3}>
<div>
<h2>PRODUCT</h2>
<p className="bar" />
<p className="ment">단 한장밖에 없는 당신만의 옷들입니다 :)</p>
</div>
<a href="#" onClick={onClick}>
상품올리기
</a>
<ProductStyle column="5">
<Product productType="all" />
</ProductStyle>
</div>
</SectionThree>
</>
);
};

export default MainSection;
hm_stom님의 프로필 이미지
hm_stom

작성한 질문수

질문하기