inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

Next + React Query로 SNS 서비스 만들기

홈탭 만들면서 Context API 적용해보기

Context API 사용시 set함수 설정 관련해서 질문 드립니다.

해결된 질문

339

공부중인사람

작성한 질문수 20

0

제가 강의를 본 이후에 개인적으로 기능 따로 만들면서 일단 백엔드 공부가 안된 상태라, 간단히 제가 당장 필요한 것들은 할 수 있는 수준에서 사용하려고 포켓베이스라는 오픈소스 DB를 활용해서 진행하고 있는데요.

로그인 관련 일부 컴포넌트 관련해서 여기서 보여준 context 기능을 적용하려고 강의 영상 참고해서
logProvider.tsx는 아래처럼 적고

"use client";
import PocketBase from 'pocketbase';
import {createContext , ReactNode, useState} from 'react';

const pb = new PocketBase('http://localhost:8090');
export const LogContext = createContext( {
    IsLogIn: pb.authStore.isValid, 
    setLog: (log : boolean) => {},

})
type Props = {children: React.ReactNode};

export default function LogProvider({children}:Props) {
    const [IsLogIn, setLog] = useState(pb.authStore.isValid);


    return (
        <LogContext.Provider value={{IsLogIn: pb.authStore.isValid, setLog: (log: boolean) =>{} }}>
            {children}
        </LogContext.Provider>
    )
}



로그인 버튼 컴포넌트에서

const LoginButton = () => {
    const [loading, setLoading] = useState(false);
    const router = useRouter();
    const {IsLogIn, setLog} = useContext(LogContext);

    // const { isLoggedIn } = useContext(AuthContext);
    let logTest = pb.authStore.isValid;
    const handleClick = async () => {
      
      if (IsLogIn) {          //로그아웃 실행
        try {       
        // console.log(IsLogIn); //기존에 로그인 된 상태라면 여기서 true

        pb.authStore.clear();
        router.replace("/")
              //로그아웃 시 홈페이지로 이동   
        } catch (error) {
          console.error(error);
        }
        logTest = pb.authStore.isValid;
        setLog(pb.authStore.isValid);
      }
      
      else {              //로그인 실행
        setLoading(true);
     
        try {
          // console.log(IsLogIn); //기존에 로그아웃 된 상태라면 여기서 false
          const authData = await pb.collection('users').authWithOAuth2({ provider: 'google' });
          console.log(authData); // 인증 데이터 확인
          // 인증 데이터를 이용하여 사용자 정보 처리, 토큰 저장 등 로직 추가
        } catch (error) {
          console.error(error);
        } finally {
          setLoading(false);          
          logTest = pb.authStore.isValid;
          setLog(pb.authStore.isValid);
          
          //디버깅용
          console.log("로그인 상태 확인")
          console.log(IsLogIn);
          console.log(pb.authStore.isValid);
          console.log(setLog)
          console.log(setLog(pb.authStore.isValid));
          console.log(logTest);
          console.log(setLog(logTest));

        }

      }
    };

    return (
      
      <div >
      <button className='logBox' onClick={handleClick} disabled={loading}>
      <img                
            src="/Google.png"       
            width={20}
            height={20}             
            style={{ position: "absolute", opacity: 0.8, marginLeft:0, marginTop: 3}} 
      />

      
        <div className="flex-LogButton" >
        {IsLogIn ? '로그아웃' : (loading ? '로그인 중...' : ' 로그인')}
        </div>

      </button>
      </div>
     
    );
  };

이런 식으로 작성을 하였습니다. 그런데 버튼기능 마지막에 디버깅용으로 넣은 console값을 보니 로그인하면 로그인은 정상적으로 진행되는데 context로 공유하고 있는 IsLogIn 값은 바뀌질 않네요... 부모 컴포넌트에서 자식컴포넌트로의 공유는 제대로 되는것으로 보입니다. 자식에게서 부모로 가는게 setLog에서 타입문제로 입력이 안되는 듯 한데, 이건 그냥 제가 타입스크립트 개념이 약해서 타입 설정을 어떻게 할지 몰라서 생기는 문제 같네요;;
아래는 디버깅용으로 넣은 7줄의 콘솔로그 기록입니다.

로그인 상태 확인

LogButtonSNS.tsx:52 false

LogButtonSNS.tsx:53 true

LogButtonSNS.tsx:54 (log)=>{}

LogButtonSNS.tsx:55 undefined

LogButtonSNS.tsx:56 true

LogButtonSNS.tsx:57 undefined

콘솔 로그 기록을 보면 logProvider.tsx
setLog: (log : boolean) => {}, 함수를 통해 boolean정보를 새로 넣어도 공유하는 IsLogIn의 value가 바뀌지 못하고 undefined라고 출력되네요. 어떻게 수정해야 할까요...

react next.js react-query next-auth msw

답변 1

1

제로초(조현영)

<LogContext.Provider value={{IsLogIn, setLog }}>

이렇게 실제 state값을 넣으셔야 합니다.

0

공부중인사람

헉! 감사합니다. 한참을 고민하느라 헤맸는데 바로 해결됐네요. 강의 코드 제대로 한번 더 봤으면 발견 했었을 텐데 무의식적으로 위에코드 복붙한 바보였네요...

캡처링부분 질문있습니다.

0

74

2

깃에 소스코드를 찾을 수 없습니다.

0

113

2

useInfiniteQuery promise와 react use 사용시 페이지 무한 로딩

0

98

1

import 파일 경로를 찾지 못 해서 에러가 발생합니다.

0

109

2

css 라이브러리 추천 부탁드립니다

0

140

2

팔로우 추천 목록이 빈 배열로 들어옵니다.

0

130

1

게시물 업로드 시 userId가 undefined로 들어가는 오류

0

119

1

useSuspenseQuery 사용 시 SSR 401 이슈 관련

0

171

1

리액트 쿼리 useinfinitequery 무한스크롤 구현 시 페이지가 이동할 경우 데이터가 보존되게 할 수 있나요??

0

184

3

폴링이 필요없는 이유

0

93

2

next Request Memoization과 react cache

0

108

2

seo 최적화 기준은 데이터 fetching인가요 아님 데이터 렌더링인가요?

0

84

2

next.js 서버fetch 에러 fallback ui 구현 방법

0

173

2

프레임워크 여론 파악법

0

125

2

필터옵션이 많은 페이지에서 서버 fetch를 하는게 맞는걸까요??

0

103

2

서버 fetch suspense 로 감싸고 새로고침 시 잠시 빈 화면이 노출된 후 fallback ui가 노출됩니다.

0

102

2

template.tsx 내 서버fetch 응답값과 클라이언트 컴포넌트 상태값 싱크가 맞지 않는 이슈

0

66

2

Auth.js 사용 시 authorize 함수가 호출되지 않습니다

0

131

2

next.js 에서 로그인에 관하여

0

138

1

Next의 route handler에 대한 질문이 있습니다.

0

101

2

게시판 리스트 만들때 use client를 어디서부터 집어넣어야할지 모르겠습니다

0

97

2

프라이빗 폴더를 해야 하는 이유가 모호한 것 같아요.

0

85

2

vanilla-extract 못찾는 문제

0

229

2

fetch 캐싱과 revalidate 관련

0

84

2