inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

173만명의 커뮤니티!! 함께 토론해봐요.

로그인을 서버액션으로 구현해봤는데 궁금한게 있습니다.

해결됨

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

로그인을 클라이언트 컴포넌트에서 서버액션을 통해 구현해봤는데, 궁금한게 생겨서 질문 드립니다. 로그인 모달의 코드입니다. "use client"; import style from "@/app/(beforelogin)/_component/login.module.css"; import { ChangeEventHandler, FormEventHandler, useState } from "react"; import { redirect, useRouter } from "next/navigation"; import { signIn } from "next-auth/react"; import { useFormState, useFormStatus } from "react-dom"; import onSubmit from "../_lib/signin"; import BackButton from "./BackButton"; function showMessage(messasge: string | null | undefined) { if (messasge === "no_id") { return "아이디를 입력하세요."; } if (messasge === "no_password") { return "비밀번호를 입력하세요."; } return ""; } export default function LoginModal() { const [state, formAction] = useFormState(onSubmit, { message: null }); const { pending } = useFormStatus(); return ( <div className={style.modalBackground}> <div className={style.modal}> <div className={style.modalHeader}> <BackButton /> <div>로그인하세요.</div> </div> <form action={formAction}> <div className={style.modalBody}> <div className={style.inputDiv}> <label className={style.inputLabel} htmlFor="id"> 아이디 </label> <input id="id" name="id" className={style.input} type="text" placeholder="" /> </div> <div className={style.inputDiv}> <label className={style.inputLabel} htmlFor="password"> 비밀번호 </label> <input id="password" name="password" className={style.input} type="password" placeholder="" /> </div> </div> <div className={style.message}>{showMessage(state?.message)}</div> <div className={style.modalFooter}> <button className={style.actionButton} disabled={pending}> 로그인하기 </button> </div> </form> </div> </div> ); } 아래는 signin.ts 의 코드입니다. "use server"; import { redirect } from "next/navigation"; import { signIn } from "@/auth"; const onSubmit = async (prevState: any, formData: FormData) => { if (!formData.get("id") || !(formData.get("id") as string)?.trim()) { return { message: "no_id" }; } if ( !formData.get("password") || !(formData.get("password") as string)?.trim() ) { return { message: "no_password" }; } let shouldRedirect = false; try { const response = await signIn("credentials", { username: formData.get("id"), password: formData.get("password"), redirect: false, }); console.log(response.status, "1"); console.log(response, "2"); shouldRedirect = true; } catch (err) { console.error(err); return { message: null }; } if (shouldRedirect) { redirect("/home"); // try/catch문 안에서 X } }; export default onSubmit; 이렇게 했을 때에, 콘솔이 이렇게 찍힙니다. 1. response가 http://localhost:3000/i/flow/login 이렇게 날라오고, status는 그에 따라 undefined 입니다. 응답이 이렇게 오면 response에 따른 status를 모르는데 에러처리를 어떻게 해야하나요 ?? 아래는 회원가입을 똑같이 서버액션으로 구현했을때에, signup.ts의 코드입니다. "use server"; import { redirect } from "next/navigation"; import { signIn } from "@/auth"; const onSubmit = async (prevState: any, formData: FormData) => { if (!formData.get("id") || !(formData.get("id") as string)?.trim()) { return { message: "no_id" }; } if (!formData.get("name") || !(formData.get("name") as string)?.trim()) { return { message: "no_name" }; } if ( !formData.get("password") || !(formData.get("password") as string)?.trim() ) { return { message: "no_password" }; } if (!formData.get("image")) { return { message: "no_image" }; } let shouldRedirect = false; try { const response = await fetch( `${process.env.NEXT_PUBLIC_BASE_URL}/api/users`, { method: "post", body: formData, credentials: "include", } ); console.log(response.status, "1"); if (response.status === 403) { return { message: "user_exists" }; } console.log(await response.json(), "2"); console.log(response, "3"); shouldRedirect = true; /*await signIn("credentials", { username: formData.get("id"), password: formData.get("password"), redirect: false, });*/ } catch (err) { console.error(err); return { message: null }; } if (shouldRedirect) { redirect("/home"); // try/catch문 안에서 X } }; export default onSubmit; 이 때에, console.log 의 결과입니다. response 응답 객체에서 await response.json()을 취했는데, OK로 나오는 이유가 궁금합니다. 로그인 구현에서 redirect를 false로 하면 client측에서 라우팅하는 것이고, true로 하면 서버쪽에서 리다이렉트 하는 것이라고 알고 있습니다. 그런데 서버 액션으로 api 호출을 하는 것인데, redirect를 false로 하고 아래 redirect를 해주어도 redirect가 되는 것인지 궁금합니다. 그리고 redirect를 true로 하면 이렇게 에러가 떠버립니다. 서버액션으로 리다이렉트 시켜주는 것이라 생각해서 true옵션을 주었는데 에러가 왜 뜨는지 궁금합니다. 바쁘실텐데 많은 질문 죄송합니다 ㅜㅜ

  • react
  • next.js
  • react-query
  • next-auth
  • msw
강주호 댓글 1 좋아요 0 조회수 412

서버 컴포넌트에서 server action 사용 질문이 있습니다.

해결됨

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

서버 컴포넌트에서 server actions 사용 중 네트워크 탭에서 응답이 안담기는 문제가 있어서 질문 드립니다. 강의에 나와있는대로 코드를 따라했는데 뭐가 문제인지 잘 모르겠습니다. 아래는 signupModal의 코드입니다. import style from "./signup.module.css"; import onSubmit from "../_lib/signup"; import BackButton from "@/app/(beforelogin)/_component/BackButton"; import { useFormState, useFormStatus } from "react-dom"; import { redirect } from "next/navigation"; function showMessage(messasge: string | null | undefined) { if (messasge === "no_id") { return "아이디를 입력하세요."; } if (messasge === "no_name") { return "닉네임을 입력하세요."; } if (messasge === "no_password") { return "비밀번호를 입력하세요."; } if (messasge === "no_image") { return "이미지를 업로드하세요."; } if (messasge === "user_exists") { return "이미 사용 중인 아이디입니다."; } return ""; } export default function SignupModal() { //const [state, formAction] = useFormState(onSubmit, { message: null }); //const { pending } = useFormStatus(); const formAction = async (formData: any) => { "use server"; let shouldRedirect = false; try { const response = await fetch( `${process.env.NEXT_PUBLIC_BASE_URL}/api/users`, { method: "post", body: formData, credentials: "include", } ); console.log(response.status); console.log(await response.json(), "abc"); if (response.status === 403) { console.log("???"); return { message: "user_exists" }; } shouldRedirect = true; } catch (err) { console.log(err); } if (shouldRedirect) { redirect("/home"); // try/catch문 안에서 X } }; return ( <> <div className={style.modalBackground}> <div className={style.modal}> <div className={style.modalHeader}> <BackButton /> <div>계정을 생성하세요.</div> </div> <form action={formAction}> <div className={style.modalBody}> <div className={style.inputDiv}> <label className={style.inputLabel} htmlFor="id"> 아이디 </label> <input id="id" name="id" className={style.input} type="text" placeholder="" required /> </div> <div className={style.inputDiv}> <label className={style.inputLabel} htmlFor="name"> 닉네임 </label> <input id="name" name="name" className={style.input} type="text" placeholder="" required /> </div> <div className={style.inputDiv}> <label className={style.inputLabel} htmlFor="password"> 비밀번호 </label> <input id="password" name="password" className={style.input} type="password" placeholder="" required /> </div> <div className={style.inputDiv}> <label className={style.inputLabel} htmlFor="image"> 프로필 </label> <input id="image" name="image" required className={style.input} type="file" accept="image/*" /> </div> </div> <div className={style.modalFooter}> <button type="submit" className={style.actionButton}> 가입하기 </button> </div> </form> </div> </div> </> ); } 아래는 핸들러 세팅입니다. http.post("/api/users", async ({ request }) => { console.log("회원가입"); return HttpResponse.text(JSON.stringify("user_exists"), { status: 403, }); // return HttpResponse.text(JSON.stringify("ok"), { // headers: { // "Set-Cookie": "connect.sid=msw-cookie;HttpOnly;Path=/;Max-Age=0", // }, // }); }), 여기서 회원가입을 누를시에 console.log() 처리한 부분은 잘 찍히고 서버쪽에서 찍은 회원가입 콘솔도 잘 찍히는 모습입니다. 네트워크탭에서 페이로드는 잘 담겼는데, 응답이 없습니다. 회원가입 누를 때 콘솔이 찍히는 것으로 보아서 포트도 9090으로 제대로 열려있고, 403응답이 오는 것으로 보아 핸들러 쪽은 제대로 작동하는 것 같습니다. 그리고 서버액션 쪽 콘솔 "???"가 찍히는 것으로 보아서 status도 403으로 잘 오는 것 같은데 리턴 메시지가 제대로 안되는 것인지 응답이 왜 없는 것인지 궁금합니다.

  • react
  • next.js
  • react-query
  • next-auth
  • msw
강주호 댓글 1 좋아요 0 조회수 604

다른 페이지갔다가 오면 게시글 불러와지는 이슈

미해결

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

게시글을 끝까지 스크롤하고, 다른 페이지에 다녀오면 다른 페이지갔다가 오면 게시글 불러와지는 이슈를 발견했습니다. index.js에서 게시글 불러오는 부분에 mainposts의 조건을 붙여서 실행하면될거같은데 차후 강의에서 해결해주시는 이슈인지 궁금합니다. 아니면 저만 그런건지 여쭤봅니다! 감사합니다.

  • react
  • redux
  • node.js
  • express
  • next.js
챠챠_ 댓글 1 좋아요 0 조회수 169

도메인과 S3연결 후 AWS 요금 과금문제 문의드립니다.

미해결

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

강의를 보고 따라하다가 오늘 보니 저번 달 사용량에 관련된 요금이 결제되었다고 메일을 받았습니다.. Amazon Virtual Private Cloud 에서 좀 많이 나왔고,, Amazon Route 53에도 요금이 나왔네요.. 총 만원정도 과금이 되었는데 어떤건지 몰라서 어디부분을 삭제해야 비용이 발생하지 않는걸까요? 강의를 잘 보고 따라했는데.. 당황스럽습니다...

  • react
  • redux
  • node.js
  • express
  • next.js
hyuri 댓글 2 좋아요 0 조회수 418

mockServiceWorker.js 파일이 프로젝트내에 포함되어 있어야 하나요?

해결됨

실무에 바로 적용하는 프런트엔드 테스트 - 1부. 테스트 기초: 단위・통합 테스트

실무에 적용하려고 하니 msw 에서 많이 막히네요 ㅠ 그래서 올려주신 깃헙 프로젝트를 샅샅히 훑어보고 있는데 mockServiceWorker.js 이 파일과 package.json에 "msw": { "workerDirectory": "public" } 요런 부분이 있더라고요. 요것들의 역할이 뭔지 알수 있을까요? msw 사이트에 가서 Getting started 를 가봐도 안나와 있는것 같아서 궁금합니다!

  • javascript
  • react
  • 소프트웨어-테스트
  • vitest
bn.kim 댓글 2 좋아요 1 조회수 297

모의문제 작업1 데이터 불러오기

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

선생님 모의문제 1을 풀려고 하는데 데이터 members를 불러오는게 이해가 안돼서요ㅜㅜ 어떻게 저장한다는 걸까요..? data: members.csv 자체에는 저장하는게 없지 않나요?

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
olive h 댓글 1 좋아요 1 조회수 402

슬라이싱 할때

미해결

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

선생님! iloc같은경우 인덱스값은 그 앞에 까지 뽑기때문에 +1 해주는 범위까지 설정 해 주는것인데, 컬럼 번호 쓸때는 해당 없는거 같네요?! quiz 2번 푸는데 iloc로 메뉴~할인율 까지 할때 범위를 :3으로 하시길래요! 위에 설명할때는 iloc때 범위를 :로 나타낼 때 마지막을 포함하지 않는다고 하셨는데, 인덱스만 포함하지 않는게 맞는거죠?

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
moonwrd 댓글 1 좋아요 0 조회수 185

회원가입 과제 완료용

미해결

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

안녕하세요!! 과제 완료해서 피드백 부탁드리고자 올렸습니다! 앞으로 잘 부탁 드립니당~ <html> <!DOCTYPE html> <html lang="ko"> <head> <title>회원가입</title> <link rel="stylesheet" href="./02-signup.css"> </head> <body> <div class="signUpContent"> <h2> 회원 가입을 위해<br> 정보를 입력해주세요 </h2> <label for="email" class="label text">* 이메일</label> <input id="email" class="input_text" type="text"> <label for="name" class="label text">* 이름</label> <input id="name" class="input_text" type="text"> <label for="password" class="label text">* 비밀번호</label> <input id="password" class="input_text" type="password"> <label for="password_chk" class="label text">* 비밀번호 확인</label> <input id="password_chk" class="input_text" type="password"> <div class="signUpChk"> <input id="gender_w" class="input_radio" type="radio" name="gender"> <label for="gender_w" class="label gender">여성</label> <input id="gender_m" class="input_radio" type="radio" name="gender"> <label for="gender_m" class="label gender">남성</label> </div> <div class="agreeChk"> <input type="checkbox" id="input_chk"> <span class="agree_text"> 이용약관 개인정보 수집 및 이용, 마케팅 활용 선택에 모두 동의합니다. </span> </div> <div class="out-line"> <div class="line"></div> </div> <button> <span>가입하기</span> </button> </di> </body> </html> <css> * { box-sizing: border-box; } h2 { font-size: 32px; color: #0068FF; font-weight: 700; line-height: 47px; } .out-line{ padding: 30px 0px; } .line { border-bottom: 1px solid #E6E6E6; } .label{ font-size: 16px; font-weight: 400; line-height: 24px; } .signUpContent{ width: 670px; height: 960px; border: 1px solid #AACDFF; border-radius: 20px; box-shadow: 7px 7px 39px rgba(0, 104, 255, .25) ; display: flex; flex-direction: column; padding: 72px 100px 70px 100px; } .label.text{ padding: 20px 20px 0 0; color: #797979; } .input_text{ border-style: none; border-bottom: 1px solid #CFCFCF; height: 60px; } .signUpChk{ display:flex; justify-content: center; align-items: center; padding: 50px 0; } .input_radio{ margin: 0 5px 0 0; width: 20px; height: 20px; } .label.gender{ padding-right: 30px; } .agreeChk{ display: flex; justify-content: center; align-items: center; } .agree_text{ height: 22px; font-size: 14px; font-weight: 400; line-height: 20px; } button{ width: 470px; height: 75px; background-color: #FFF; border: 1px solid #0068FF; border-radius: 10px; } button > span { font-size: 18px; font-weight: 400; color: #0068FF; }

  • react
  • node.js
  • seo
  • graphql
  • next.js
개발하는 알파카 댓글 2 좋아요 0 조회수 302

회원가입하고나서 로그인 풀리는 현상

미해결

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

안녕하세요 회원가입 후에 로그인이 된 상태여야 하는데 로그인이 풀리는 현상을 확인했습니다. 왜 인지 찾아보니 프론트에선 회원가입 후 더미데이터를 가지고 로그인 하고 있었음 백단에서는 회원가입 유저의 정보를 내려주지 않고 있었음. 이런 경우때문인 것 같았습니다. 그래서 회원가입 후 메인 페이지로 라우팅 되면 메인페이지에서 로그인 유무를 판단하는 로직이 실행되고, 더미데이터로 있던 데이터를 로그인 풀어버려서 그런게 아닐까 합니다. 그러면 /back/routes/user.js const user = await User.create({ email, nickname, password: hashedPassword, }); 여기서 user정보를 내려줘야할거 같은데 여기서 더 필요한 post, image같은 이미지는 어떻게 추가해야하는지 궁금합니다.

  • react
  • redux
  • node.js
  • express
  • next.js
챠챠_ 댓글 1 좋아요 0 조회수 166

센셕4 게시물 불러오기 postcard.js에서 post.User.nickname[0]에러

미해결

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

안녕하세요 센셕4 게시물 불러오기 postcard.js에서 post.User.nickname[0]에러가 발생해서 처음엔 간단하게 /components/postcard.js <Card.Meta avatar={<Avatar>{post.User?.nickname[0]}</Avatar>} title={post.User?.nickname} description={<PostCardContent postData={post.content} />} /> 이런식으로 해결했었습니다. 아 같은 파일 위치에서 {id && post.User?.id === id ? ( <> <Button type='primary' key='modify'> 수정 </Button> <Button type='danger' key={"delete"} onClick={onRemovePost} loading={removePostLoading}> 삭제 </Button> </> ) : ( <Button type='dashed' key={"report"}> 신고 </Button> )} post.User?.id 이것도 같은 식으로 처리했었습니다. 그런데 제로초님 코딩을 몇번 다시봤더니 비슷한 에러가 코멘트에서 났었는데 /routes/posts.js const express = require("express"); const router = express.Router(); const { Post, User, Image, Comment } = require("../models"); // GET /posts 여러 게시글 가져오기 router.get("/", async (req, res, next) => { try { const posts = await Post.findAll({ limit: 10, include: [ { model: User, attributes: ["id", "nickname"], }, { model: Image, }, { model: Comment, include: [ { model: User, attributes: ["id", "nickname"], }, ], }, ], }); res.status(200).json(posts); } catch (error) { console.error(error); next(error); } }); module.exports = router; 이런식으로 데이 필요한 id, nickname을 넣어주셔서 ?를 붙이지 않고 해결하셨더라구요. 혹시 저 nickname부분도 위와같이 백단에서 코드를 수정해서 고칠수 있을까요? 따라서 해봤는데 잘 안되서 여쭤봅니다.

  • react
  • redux
  • node.js
  • express
  • next.js
챠챠_ 댓글 3 좋아요 0 조회수 354

리액트쿼리 어떤부분이 잘못되었을까요?

해결됨

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

안녕하세요. 인피니티스크롤 을 따라하는데 잘안되서요. const queryClient = new QueryClient(); await queryClient.prefetchInfiniteQuery({ queryKey: ["member", "sales", sawonCode], queryFn: getSales, initialPageParam: 0, }) const dehydratedState = dehydrate(queryClient); return <> <Suspense fallback={<Loading />}> <HydrationBoundary state={dehydratedState}> <SalesList sawonCode={sawonCode} /> </HydrationBoundary> </Suspense> </> const { data, fetchNextPage, hasNextPage, isFetching, } = useInfiniteQuery<Item[], Object, InfiniteData<Item[]>, [_1: string, _2: string, _3: number], number>({ queryKey: ["member", "sales", sawonCode], queryFn: getSales, initialPageParam: 0, getNextPageParam: (lastPage) => lastPage.at(-1)?.page, staleTime: 60 * 1000, // fresh -> stale, 5분이라는 기준 gcTime: 300 * 1000, }); const { ref, inView } = useInView({ threshold: 0, delay: 0, }); useEffect(() => { if(inView) { console.log(data); !isFetching && hasNextPage && fetchNextPage(); } }, [inView, isFetching, hasNextPage, fetchNextPage]); useEffect에 콘솔에찍은 data는 undefined 이 찍히고 그후에 getSales에 찍은 api 로 가져온 데이터가 찍힙니다. 어떤게 잘못되서 data에 값이 안들어가는지 몇시간을 봐도 잘모르겠네요..ㅜㅜ

  • react
  • next.js
  • react-query
  • next-auth
  • msw
11m48a2c 댓글 1 좋아요 0 조회수 253

'str' object is not callable

미해결

[리뉴얼] 파이썬입문과 크롤링기초 부트캠프 [파이썬, 웹, 데이터 이해 기본까지] (업데이트)

안녕하세요 수업 듣는중 문제 푸는 21번 강의에서 'str' object is not callable 나와서 알려주신대로 코드를 작성했다가, 안되서 강의자료 복사에서 실행해도 error 납니다. 이런 경우에는 왜 이런 버그가 나오나요? 문제를 풀다가 1번도 아니고 여러 문제들이 계속 같은 문구가 나와서 이렇게 문의드립니다. 답변 주시면 감사하겠습니다 수업 21번 - 본 강의 영상 학습 관련 문의에 대해 답변을 드립니다. (어떤 챕터 몇분 몇초를 꼭 기재부탁드립니다) - 이외의 문의등은 평생강의이므로 양해를 부탁드립니다 - 현업과 병행하는 관계로 주말/휴가 제외 최대한 3일내로 답변을 드리려 노력하고 있습니다 - 잠깐! 인프런 서비스 운영(다운로드 방법포함) 관련 문의는 1:1 문의하기를 이용해주세요.

  • python
  • 웹-크롤링
syp837 댓글 3 좋아요 0 조회수 2376

NextAuth Credentials authorize의 결과 타입

미해결

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

return { name: user.nickname, email: user.email, image: user.profileImage, ...user, }; 강의에서 user를 그대로 리턴해서 사용하지 않고 user를 커스텀해준 것을 보았습니다. 현재 return하는 값은 Typescript에서 지정한 User 타입을 그대로 사용하면서 수정해서 값을 할당해줬다고 이해했는데 추가로 들어가는 ...user 는 어디에서 사용할 수 있는지 궁금합니다. 추가로 제 코드에는 반환하는 정보가 더 많은데 어떤 식으로 값을 할당해서 사용할 수 있는지 궁금합니다. 타입을 하나 만들어서 확장해서 사용하고 싶은데 따로 파일을 만들어줘야 할까요?

  • react
  • next.js
  • react-query
  • next-auth
  • msw
이우열 댓글 1 좋아요 0 조회수 281

로그인 기능을 next-auth와 수업에서 처럼 직접 구현하는 것 어떤걸 더 추천하시나요?

미해결

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

안녕하세요 제로초님 강의를 따라가다 보니 로그인 부분이 엄청 복잡하더라구요, 개인적으로 next-auth을 사용하면 되게 간편했던걸로 기억하는데 제로초님은 로그인 기능을 만들게 된다면 next-auth와 수업에서 처럼 직접 구현하는 것 어떤걸 더 추천하실지 궁금합니다. 직접구현하는게 로그인이 어케 이뤄지는지 이해할수있어서 좋은거같은데 여쭤보고 싶었습니다!

  • react
  • redux
  • node.js
  • express
  • next.js
챠챠_ 댓글 1 좋아요 0 조회수 290

changer라는 컴포넌트를 사용하는 이유

해결됨

기초부터 배우는 Next YTMusic 클론 코딩 (with next.js 14, UI 마스터)

HeaderBgChanger라는 컴포넌트는 단순히 서버 컴포넌트에서 react hook을 사용할 수 없기 때문에 만드는 컴포넌트인지 궁금합니다. 또 이렇게 컴포넌트를 만들 경우에 렌더링 될 때 영향을 주는 부분은 없는지 궁금합니다.

  • react
  • 인터랙티브-웹
  • 클론코딩
  • next.js
  • tailwind-css
  • zustand
김택수 댓글 2 좋아요 1 조회수 293

Qouta 리스트에 아무것도 안나옵니다.

미해결

파이썬 알고리즘 트레이딩 파트1: 알고리즘 트레이딩을 위한 파이썬 데이터 분석

spot이라고 검색을 하면 머라고 나와야하는데 아무것도 안나옵니다.. 제가 빠트린 작업이 있을까요?

  • python
  • 머신러닝
  • pandas
  • 객체지향
  • 퀀트
  • 병렬-처리
이승빈 댓글 4 좋아요 2 조회수 424

Nextjs fetch, react-query 캐시 개념

미해결

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

Nextjs fetch도 캐시가 지원되고, react-query도 캐시가 지원되는걸로 이해를 했는데요 문득 궁금한 점이 생겨서 질문 드립니다. Nextjs fetch와 react-query에서의 캐시는 같은 개념인가요? 아니면 서로 다른 개념인가요? 왜 Nextjs fetch를 안 쓰고 react-query를 쓰는 걸까요? Nextjs fetch는 어떨 때 쓰고 react-query는 어떨 때 쓰는 건가요? 감사합니다.

  • react
  • next.js
  • react-query
  • next-auth
  • msw
주니어에요 댓글 1 좋아요 0 조회수 455

Suspense 컴포넌트의 fallback 요소로 클라이언트 컴포넌트 전달?

해결됨

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

안녕하세요. Suspense 컴포넌트의 fallback 요소로 서버 컴포넌트 전달은 문제가 없는데, 내부적으로 useEffect와 타이머를 사용하는 클라이언트 컴포넌트를 전달했더니 해당 훅과 관련된 내용은 모두 스킵되고 그냥 초기 렌더링 내용만 나오는 것 같은데, 애초에 클라이언트 컴포넌트는 전달이 불가능한걸까요? 클라이언트 컴포넌트 사용 의도는 1초마다 로딩바 게이지가 증가하는 모습을 보여주고 싶어서 사용해보려고 했습니다. 공식 문서를 봐도 해당 내용에 대해서는 언급이 없는 것 같습니다. 감사합니다.

  • react
  • next.js
  • react-query
  • next-auth
  • msw
Yu Byung Suk 댓글 1 좋아요 0 조회수 359

useQuery 오류가 발생합니다

미해결

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

"use client"; import { useQuery } from "@tanstack/react-query"; import { getPostRecommends } from "@/app/(afterLogin)/home/_lib/getPostRecommends"; import Post from "@/app/(afterLogin)/_component/Post"; import { Post as IPost } from "@/model/Post"; export default function PostRecommends() { const { data, error, isLoading } = useQuery<IPost[]>({ queryKey: ["posts", "recommends"], queryFn: getPostRecommends, // gcTime은 staleTime보다 길어야한다 staleTime: 5 * 1000, // 새로 가져온 데이터를 몇 초 후에 fresh에서 stale로 바꿀 것인지 gcTime: 300 * 1000, }); if (isLoading) { return <div>Loading...</div>; } if (error) { return <div>Failed to load posts</div>; } return data?.map((post) => <Post key={post.postId} post={post} />); } react query에서 에러가 발생합니다 이유는 모르겠지만 useQuery부분에서 에러가 발생하는 것 같습니다 getPostRecommend.ts는 이렇게 작성한 상태입니다 export async function getPostRecommends() { const res = await fetch(`http://localhost:9090/api/postRecommends`, { next: { tags: ["posts", "recommends"], }, //캐시를 저장하라고 지정하는 태그 // 너무 강력하게 캐싱을 하면 새로운 데이터가 안불러와 질 수 있다 // 이런 일을 방지하기위해 새로고침을 해야하는 이때 tags를 사용한다 }); // The return value is *not* serialized // You can return Date, Map, Set, etc. if (!res.ok) { // This will activate the closest `error.js` Error Boundary throw new Error("Failed to fetch data"); } // 이렇게 하면 recommends를 키로 가지고 있는 서버에 있는 캐시가 날아감 // revalidateTag("recommends") // home으로 온 요청이 왔을때 페이지 전체의 캐시를 새로고침한다 // revalidatePath('/home') return res.json(); } 근데 getPostRecoomed.ts가 잘못된거 같지는 않은것이 처음 작동하는 queryClient.prefetchQuery 는 잘 작동합니다

  • react
  • next.js
  • react-query
  • next-auth
  • msw
i1004gy 댓글 2 좋아요 0 조회수 342

하이드레이션 에러

미해결

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

Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Did not expect server HTML to contain a <a> in <div>. See more info here: https://nextjs.org/docs/messages/react-hydration-error 이런 에러가 발생하는데 초반 랜더링과 뭐가 다르거나 랜덤 데이터를 사용하면 오류가 나온다는 것 같아서 혹시 faker를 사용해서 생긴느 에러인지 궁금합니다 "use client"; import { useQuery } from "@tanstack/react-query"; import { getPostRecommends } from "@/app/(afterLogin)/home/_lib/getPostRecommends"; import Post from "@/app/(afterLogin)/_component/Post"; import { Post as IPost } from "@/model/Post"; export default function PostRecommends() { const { data } = useQuery<IPost[]>({ queryKey: ["posts", "recommends"], queryFn: getPostRecommends, // gcTime은 staleTime보다 길어야한다 staleTime: 60 * 1000, // 새로 가져온 데이터를 몇 초 후에 fresh에서 stale로 바꿀 것인지 }); return data?.map((post) => <Post key={post.postId} post={post} />); } 여기에서 queryFn: getPostRecommends 이 부분을 지워도 정상 작동하는데 queryFn: getPostRecommends 이것이 하는 기능이 무엇인가요? 또 여기에서 Retech와 invalidate를 눌러도 트윗이 변하지 않습니다 혹시 위 에러와 관련이 있나요?

  • react
  • next.js
  • react-query
  • next-auth
  • msw
i1004gy 댓글 2 좋아요 0 조회수 498

인기 태그

인프런 TOP Writers

주간 인기글