69,300원
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결Next + React Query로 SNS 서비스 만들기
tailwind 질문입니다.
테일윈드랑 비교하셨는데욥!tailwind는 결국 프레임워크이고다른 css 는 직접 작성을 해야하니 목적이 다르다고 생각했는데요.css를 직접 작성하신 이유가있을까요??테일윈드를 쓰면 호불호가 있긴 하겠지만 강의특성상 css 를 빠르게 사용할수있다고 생각되어서요
- 미해결Next + React Query로 SNS 서비스 만들기
앱라우터를 쓰면서 컴포넌트 분류가 궁금합니다...
제로초님 강의를 보면서 새롭게 페이지 작업을 하고 있는데 최다 클라이언트 컴포넌트로 작업이 되고 잇어서 고민이 됩니다.예를들어 쇼핑몰의 상세페이지를 만드는데 좋아요나 판매하기 기타등등 여기에 써야하는 click이벤트 들때문에 서버컴포넌트를 쓰기는 애매해서 클라이언트 컴포넌트로 작업 중인데... 모든 컴포넌트들이 이런 상황입니다ㅠㅠ 혹시 클라이언트 컴포넌트와 서버컴포넌트를 나누는 기준 같은거 알수 잇을까요??
- 미해결Next + React Query로 SNS 서비스 만들기
next.config.js
next.config.js 파일이 아닌 next.config.mjs 파일이 생기는데 import 문을 사용하면 해결이 되는 것 같습니다. 그런데 기본적으로 js -> mjs파일이 셋팅되는 이유와 mjs파일을 그대로 쓰는게 나을지 js 파일로 사용하면 될지 궁금합니다.
- 미해결Next + React Query로 SNS 서비스 만들기
msw 실행 방식에 관해서
안녕하세요 선생님msw 방식에 대해서 강의해주신것과 다른 질문들을 보다가 궁금한게 생겨서 문의드립니다.강의에서는 클라리언트 환경에서는 mockServiceWorker.js가 api(요청)를 가로채서, http.ts(서버)로 보낸다.그리고 handlers.ts가 실행된다. 이렇게 말씀해주셨는데, 다른질문에서msw express 서버는 next server에서 요청보내는 걸 모킹하는 것이고요. MSWComponent는 브라우저에서 요청을 보내는 걸 모킹하는 것 이런 답변을 보았습니다. 그렇다면 제가 이해하기로는기본적으로는 아래와 같이 실행이 되는데,클라리언트 환경에서는 mockServiceWorker.js가 api(요청)를 가로채서, http.ts(서버)로 보낸다.그리고 handlers.ts가 실행 next server에서 요청받은 것은(ssr) createMiddleware에서 받아서 handlers로 보내고클라이언트에서 요청받은 것은 MSWComponent에서 받아서, brwoser로 보낸다음에 handlers로 보낸다로 이해하면 될까요?
- 미해결Next + React Query로 SNS 서비스 만들기
modal에 intercept route를 사용하는 이유가 새로고침했을때를 위함인가요?
안녕하세요 선생님.수업을 듣다 궁금한게 생겨서 문의 드립니다.모달창만 열려면 intercept를 쓰지 않고 패러렐 라우트에 일반라우트 폴더를 넣어도 작동하더라구요. (beforelogin)/@modal2/i/flow/login하지만 새로고침때는 그 페이지를 찾을 수 없기에 not-found.tsx를 호출하는걸 확인했습니다.modal에 intercept route를 사용하는 이유가 새로고침했을때를 위함이라고 이해하면 될까요? 혹은 다른 추가적인 이유가 더 있는지 궁금합니다.
- 해결됨Next + React Query로 SNS 서비스 만들기
vercel 배포했는데 잘 되다가 안들어가집니다.
안녕하세요 제로초님 강의 잘 듣고있었는데, 강의 질문이 아니라 다른 질문이라 죄송합니다. 당장 다음주 월요일부터 심사가 시작되는 공모전에 나갈 프로젝트인데 잘 되던게 갑자기 안들어가져서요 ㅠㅠㅠㅠ 약 한달전에 배포 cicd 설정 다 해놓고 어제밤까지만해도 문제없이 잘 들어가졌는데 오늘 갑자기 안들어가지네요.. dns_probe_finished_nxdomain 이라고 뜬대요 근데 제 pc로는 캐시를 다 삭제하고 들어가도 잘 되거든요 근데 모바일에선 안되고 다른 사람은 안들어가진다고 하는데 원인이 뭘까요..? 제 pc에서도 크롬에서만 들어가지고 다른 브라우저는 안됩니다. 메일로 vercel에서 뭐 온것도 없습니다.. vercel 설정에서 domains에 문제도 없구요.메일로 vercel에서 뭐 온것도 없습니다.빌드 에러도 없구요무료플랜이었어서 유료플랜으로 업그레이드 했는데도 똑같습니다.. ㅠㅠ 도메인이름은 공개적으로 못 적지만 개인적으로 알려드리겠습니다. ci/cd 되어있어서 main에 계속 push해봐도 빌드 잘 되는데 들어가지지를 않아요...
- 미해결Next + React Query로 SNS 서비스 만들기
searchParams props
안녕하세요search 페이지 props에서 searchParams props가 기본적으로 제공된다고 알고있는데 저는 콘솔로 찍어보니 나오지 않습니다..! 혹시 제가 잘못적용한건지 아니면 다시한번 확인해야 될곳이 있을까요?/import SelectBox from "@/components/common/SelectBox"; import SelectStack from "@/components/common/SelectStack"; import Peoples from "@/components/people/Peoples"; import SearchForm from "@/components/common/SearchForm"; type Props = { searchParams: { page: string; size: string; sort?: string; keyword?: string; position?: string; teckStack?: string; }; }; export default function Page({ searchParams }: Props) { console.log("??", searchParams); return ( <div> <div className="relative flex items-center gap-4"> <h1 className="text-[36px] font-bold">People</h1> </div> <div className="flex justify-between"> <div className="flex gap-3"> <SelectBox options={option} title="포지션" /> <SelectStack /> </div> <SearchForm keyword={searchParams.keyword as string} /> </div> <Peoples searchParams={searchParams} /> </div> ); }
- 미해결Next + React Query로 SNS 서비스 만들기
하트 클릭 시 Hearts 배열 업데이트 관련 질문
하트 버튼을 눌러서 Heart 배열에 userId를 넣어줄 때Hearts: [...value.pages[pageIndex][index].Hearts, { userId: session?.user?.email as string }],위와 같이 기존 Hearts 배열에 본인 userId 값을 추가하는 방식이 아니라Hearts: [{ userId: session?.user?.email as string }],이렇게 Hearts 배열에 본인 userId 값만 넣어주는 이유는 무엇인가요? 어차피 보여지는 결과는 동일하기 때문에 굳이 배열을 복사하는 과정을 거치지 않아 성능을 높이기 위함이라고 보면 될까요?
- 미해결Next + React Query로 SNS 서비스 만들기
프리즈마로 api만드시는 강의는 언제쯤 나올지 알 수 있을까요?
안녕하세요 선생님프리즈마로 api만드시는 강의는 언제쯤 나올지 알 수 있을까요?직접만든 api랑 이번수업에서 배울next로 플젝을 만들고 싶은데 궁금합니다.
- 미해결Next + React Query로 SNS 서비스 만들기
next-auth로 다시 한번 질문을 올립니다...
공지의 올려주신대로 auth.ts 를 수정하였으며 loginModal 의 redirect:trueexport const { handlers: { GET, POST }, auth, signIn, } = NextAuth({ pages: { signIn: "/i/flow/login", newUser: "/i/flow/signup", }, callbacks: { // async signIn() // async authorized({ auth }) { // if (!auth) { // // 쿠키가 없으면 로그인 페이지로 돌리기 // return NextResponse.redirect("http://localhost:3000/i/flow/login"); // } // return true; // }, }, providers: [ CredentialsProvider({ async authorize(credentials) { const authResponse = await fetch( `${process.env.NEXT_PUBLIC_BASE_URL}/api/login`, // NEXT_PUBLIC_BASE_URL=http://localhost:9090 { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ id: credentials.username, password: credentials.password, }), } ); // 여기 주목!!! 서버에서 에러가 발생할 때 그 에러 내용이 서버에 담겨 있을 겁니다. console.log(authResponse.status, authResponse.statusText); if (!authResponse.ok) { const credentialsSignin = new CredentialsSignin(); if (authResponse.status === 404) { credentialsSignin.code = "no_user"; } else if (authResponse.status === 401) { credentialsSignin.code = "wrong_password"; } throw credentialsSignin; } const user = await authResponse.json(); console.log("user", user); // id, name, image, email만 허용 return { id: user.id, name: user.nickname, image: user.image, }; }, }), ], }); 아래와 같은 오류가 계속 해서 발생하고 있습니다. TypeError: next_dist_server_web_exports_next_request__WEBPACK_IMPORTED_MODULE_0__ is not a constructor pakage.json 의 버젼은 아래와 같이 사용하고 있고요 "@auth/core": "^0.27.0", "next-auth": "^5.0.0-beta.16",혹시 이 부분의 같은 에러가 나오신 분들 중 해결 하신 분들이 있을까요?
- 미해결Next + React Query로 SNS 서비스 만들기
제로초님 에러를 해결 하다가 전달 드립니다 ㅠㅠ
react-query를 사용 하고 있는 그중 useQuery를 사용 하고 있습니다 네트워크 탭상에서는 한번만 호출 햇는데 console에서는 회색으로 아래와 같이 두번 호출 한것 처럼 나오는데 이건 어떻게 못막을까요?!조건을 걸어서 확인을 해봤지만 계속 해서 나오더라구여 ㅠㅠ두번의 호출인지 소켓을 요청 했을때 두번을 요청 하더라구여 ㅜㅜ
- 미해결Next + React Query로 SNS 서비스 만들기
router.replace() 질문
팔로우 버튼을 누르면 로그인 화면으로 가도록 기능을 넣어봤습니다.FollowRecommend 컴포넌트에서 router.replace('/i/flow/login'); 를 하면 notfound 페이지가 뜹니다. (당연히 router.replace('/home')을 해도 마찬가지 입니다.<- /i/flow/login으로 가기때문)그러나 이 상태에서 새로고침하면 로그인 화면 잘 뜹니다.이렇게 root 경로로는 잘 넘어가서 일단은 메인화면으로 해놨는데, 왜 이런 현상이 발생하는 걸까요..? 감사합니다.
- 미해결Next + React Query로 SNS 서비스 만들기
is not valid JSON 에러 ..!
import { http, HttpResponse } from "msw"; const testData = [ { result: "success", userId: 2, nickname: "닉네임", favoriteCount: 223, viewCount: 336, position: "Backend", userFileUrl: "/Users/user/Desktop/pictures/userPicture.jpg", year: "경력없음", techStack: "react, java, ---", softSkill: "소통, 적극성, ---", links: "http://블로그주소", alarmStatus: true, content: "안녕하세요 구인 중입니다", }, ]; export const handlers = [ http.post("/api/post", () => { return HttpResponse.text(JSON.stringify("ok")); }), http.get("/api/get", ({ request }) => { console.log("request", request); return HttpResponse.json(testData); }), ]; export default handlers;"use client"; import { redirect } from "next/navigation"; export default function Home() { const handleClick = () => { fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/get`, { method: "get", }) .then((res) => console.log("res", res.json())) // JSON 형식으로 변환된 데이터를 가져옴 .then((data) => console.log("res?", data)); // JSON 데이터를 로그에 출력 }; return ( <> <div> <button onClick={handleClick}>test btn</button> <p>계정을 생성하세요</p> <form> <div> <> <label htmlFor="id">아이디</label> <input type="text" id="id" name="id" required /> </> <> <label htmlFor="name">이름</label> <input type="text" id="name" name="name" required /> </> <button type="submit">가입하기</button> </div> </form> </div> </> ); } browser.ts, handlers.ts, http.ts, MSWComponent.tsx, server.ts 는 제로초님과 다 동일하게 설정하였고 get부분에서 위와같이 하였는데 Unexpected token '<', "<!DOCTYPE "... is not valid JSON 라는 에러가 계속 발생합니다 ㅠㅠ 어떤부분이 문제일까요.. !console.log("res", res.json())) 이부분에서 res만 콘솔로 확인하면 이렇게 나옵니다..!
- 미해결Next + React Query로 SNS 서비스 만들기
cookies().toString() 질문
getUserServer headers 내부 Cookie에 cookies().toString()을 통해 넣어주셨는데 쿠키 안에 있는 모든 값들을 통으로 toString 변환하여 넣어준 이유가 어떤 이유일까요?
- 미해결Next + React Query로 SNS 서비스 만들기
답글 api 관련 질문
[username]/status/[id] 페이지에 접근했을 때해당 게시글의 답글을 리액트 쿼리의 인피니트 스크롤을 통해 가져오는데제로초님이 직접 배포하신 z.nordbird.com도 그렇고 제가 강의를 통해 만들고 있는 페이지에 인피니트 스크롤을 적용해봐도리액트 쿼리를 통해 가져오는 데이터가 계속 중복이 되는데(cursor 값이 증가하면서 다음 답글을 가지고 오지 못하고 어떤 cursor를 기준으로 이보다 작은 값을 가지는 답글만 fetching 됨)코드상의 오류는 아니고 백엔드 설계가 그렇게 되어 있는 거죠? 답글 무한 스크롤 결과(pageParam이 96을 넘어가지 못함)답글 인피니트 스크롤 부분 코드는 배포된 페이지 깃에 올라온 내용과 동일합니다.
- 미해결Next + React Query로 SNS 서비스 만들기
provider 가 안되요...
안녕하세요 provider 따라해보는중 다른데는 잘되는데 안되는곳이 있어 문의드립니다. "use client" import {createContext, ReactNode, useState} from "react"; const currentYear = new Date().getFullYear(); const currentMonth = new Date().getMonth() + 1; export const FilterContext = createContext({ year: currentYear, setYear: (value: number) => {}, month: currentMonth.toString().padStart(2, "0"), setMonth: (value: string) => {}, }); type Props = { children: ReactNode }; export default function FilterProvider({ children }: Props) { const [ year, setYear ] = useState(currentYear); const [ month, setMonth ] = useState(currentMonth.toString().padStart(2, "0")); return ( <FilterContext.Provider value={{ year, setYear, month, setMonth }}> {children} </FilterContext.Provider> ); } const { year, setYear, month, setMonth } = useContext(FilterContext); const [selectBox2, setSelectBox2] = useState(false); const [selectBox3, setSelectBox3] = useState(false); {Array.from({ length: year - 2019 }, (_, index) => year - index).map((item) => ( <li key={item} onClick={() => { setSelectBox2(false); setYear(item); console.log(item); }}>{item}</li> ))} {Array.from({ length: 12 }, (_, index) => (index + 1).toString().padStart(2, "0")).map((item) => ( <li key={item} onClick={() => { setSelectBox3(false); console.log("month",item); setMonth(item); }}>{item}</li> ))}yser, month 가 업데이트가 될질 않아서요. 콘솔에는 찍히는데 값이 변경이 안되는 이유를 모르겠습니다.
- 미해결Next + React Query로 SNS 서비스 만들기
useMutation의 onError에 관하여 질문있습니다.
안녕하세요. 제로초님 항상 좋은 강의 감사드립니다. 해당 강의에서 팔로우 api에 의도적으로 에러를 일으켜 보았는데, onError에서 캐치하지 못하는 것을 확인했습니다. const follow = useMutation({ mutationFn: (userId: string) => { // console.log('follow', userId); return fetch( `${process.env.NEXT_PUBLIC_BASE_URL}/api/users/${userId}/follow`, { credentials: 'include', method: 'post', } ); }, ... onError(error, userId: string) { ... } 그래서 밑에와 같이 바꾸어보니 onError에서 캐치하여 롤백이 정상적으로 되었습니다. mutationFn: async (userId: string) => { const response = await fetch( `${process.env.NEXT_PUBLIC_BASE_URL}/api/users/${userId}/follow`, { credentials: 'include', method: 'post', } ); if (!response.ok) { throw new Error('팔로우 실패'); } return response; },혹시 본 강의 코드대로 하면 onError에서 원래 캐치해야하는데 안 되는 것인지 아니면 수강생들에게 숙제로 낸 것인지 궁금합니다.
- 해결됨Next + React Query로 SNS 서비스 만들기
무한 스크롤 prefetch SSR 로그인 쿠키 관련 질문
안녕하세요 제로초님,api/users/{id} 에서 Followers 데이터는제가 상대방을 팔로잉 했고 로그인 정보 쿠키가 잘 전달되면상대방의 팔로워 수와 관계없이 제가 팔로우 했다면 저의 userId만 배열에 담겨서 돌아오기 때문에 api/posts/followings 혹은 api/posts/recommends의Comments 데이터도 이와 동일할 것이라고 생각했습니다. 추천 포스트는 prefetch를 진행하고(Suspense를 적용하지 않음)팔로잉 포스트는 SSR을 할 때 서버에서 로그인 여부를 판단하는 쿠키를 함께 보내야 하기 때문에prefetch에서는 next의 cookies를 사용해서 쿠키를 전달했습니다.하지만 Comments 배열에 로그인 유저가 아닌 다른 유저의 id도 함께 날라옵니다. 추천 포스트가 아닌 팔로잉 포스트는 useSuspenseInfiniteQuery를 사용했는데로그인 유저의 id만 잘 전달받았습니다. 이게 Suspense 내부에 있어서 그런가 싶어서Suspense를 걷어내고 prefetch만 사용했을 때도동일하게 로그인 유저가 아닌 다른 유저의 id도 확인할 수 있었습니다.왜 로그인 쿠키를 보내는데도 다른 유저의 정보도 날라오는지 궁금합니다.어디가 잘못된 것일까요?useSuspenseInfiniteQuery를 사용한 팔로잉 포스트는 추천 포스트와 어떤점이 달라서 정상 작동한 것일까요?추가) 이 글 작성하고 추천 포스트에도 useSuspenseInfiniteQuery를 적용했는데 팔로잉 포스트처럼 안 나오고 이전과 동일하게 다른 유저의 id도 함께 날라오는데 왜 그럴까요? 추천 포스트 결과현재 로그인 한 유저의 id는 'jihwan3'Comments에 'jihwan2'도 함께 날라오는중 팔로잉 포스트 결과현재 로그인 한 유저의 id는 'jihwan3'Comments에 'jihwan3'만 날라오는 중Hearts도 jihwan3가 좋아요를 안 눌러서 비어있는 모습page.tsximport { Suspense } from "react"; import { auth } from "@/auth"; import { Container } from "./_component/styled"; import HomeTab from "./_component/HomeTab"; import HomeTabProvider from "./_component/HomeTabProvider"; import PostForm from "./_component/PostForm"; import SuspenseDecider from "./_component/SuspenseDecider"; import Loading from "../_component/LoadingUI"; export default async function Home() { const session = await auth(); return ( <Container> <HomeTabProvider> <HomeTab></HomeTab> <PostForm me={session} /> <Suspense fallback={<Loading />}> {/* @ts-expect-error Server Component */} <SuspenseDecider /> </Suspense> </HomeTabProvider> </Container> ); } SuspenseDecider.tsximport { QueryClient, HydrationBoundary, dehydrate } from "@tanstack/react-query"; import getRecommendPosts from "../_lib/getRecommendPosts"; import getRecommendPostsServer from "../_lib/getRecommendPostsServer"; import PostDisplay from "./PostDisplay"; export default async function SuspenseDecider() { const queryClient = new QueryClient(); await queryClient.prefetchInfiniteQuery({ queryKey: ["posts", "recommends"], queryFn: getRecommendPostsServer, initialPageParam: 0, getNextPageParam: (lastPage, pages) => lastPage.at(-1)?.postId, pages: 1, }); return ( <HydrationBoundary state={dehydrate(queryClient)}> <PostDisplay /> </HydrationBoundary> ); }getRecommendPostsServer.tsimport { QueryFunction } from "@tanstack/query-core"; import { Post as IPost } from "@/model/Post"; import { cookies } from "next/headers"; type Prop = { pageParam: number; }; const getRecommendPostsServer: QueryFunction<IPost[], [_1: string, _2: string], number> = async ({ pageParam }: Prop) => { const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/posts/recommends?cursor=${pageParam}`, { method: "get", headers: { Cookie: cookies().toString(), }, }); if (response.ok) return response.json(); else throw new Error(); }; export default getRecommendPostsServer;postDisplay.tsx"use client"; import { use } from "react"; import { TabContext } from "./HomeTabProvider"; import RecommendPosts from "./RecommendPosts"; import FollowingPosts from "@/app/(afterLogin)/home/_component/FollowingPosts"; export default function PostDisplay() { const { selectedMenu } = use(TabContext); if (selectedMenu === "recommend") { return <RecommendPosts />; } return <FollowingPosts />; } RecommendPosts.tsx"use client"; import { useEffect, Fragment } from "react"; import { InfiniteData, useInfiniteQuery } from "@tanstack/react-query"; import { useInView } from "react-intersection-observer"; import getRecommendPosts from "../_lib/getRecommendPosts"; import Post from "../../_component/Post"; import { Post as IPost } from "@/model/Post"; export default function RecommendPosts() { const { isFetching, fetchNextPage, hasNextPage, data } = useInfiniteQuery<IPost[], Object, InfiniteData<IPost[]>, [_1: string, _2: string], number>({ queryKey: ["posts", "recommends"], queryFn: getRecommendPosts, initialPageParam: 0, getNextPageParam: (lastPage) => lastPage.at(-1)?.postId, }); const { ref, inView } = useInView({ /* Optional options */ threshold: 0, delay: 100, }); useEffect(() => { if (inView) !isFetching && hasNextPage && fetchNextPage(); }, [inView, isFetching, hasNextPage, fetchNextPage]); if (!data) return null; // 이거 에러는...? type error인데.. -> InfiniteData로 해결 return ( <> {data.pages.map((ele: IPost[], idx: number) => ( <Fragment key={idx}> {ele.map((post: IPost) => ( <Post key={post.postId} post={post}></Post> ))} </Fragment> ))} <div ref={ref} style={{ height: "50px" }}></div> </> ); } getRecommendPost.tsimport { QueryFunction } from "@tanstack/query-core"; import { Post as IPost } from "@/model/Post"; type Prop = { pageParam: number; }; const getRecommendPosts: QueryFunction<IPost[], [_1: string, _2: string], number> = async ({ pageParam }: Prop) => { const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/posts/recommends?cursor=${pageParam}`, { method: "get", credentials: "include", }); if (response.ok) return response.json(); else throw new Error(); }; export default getRecommendPosts; FollowingPosts.tsx"use client"; import { Fragment, useEffect } from "react"; import { useSuspenseInfiniteQuery, InfiniteData } from "@tanstack/react-query"; import { useInView } from "react-intersection-observer"; import getFollowingPosts from "../_lib/getFollowingPosts"; import Post from "../../_component/Post"; import { Post as IPost } from "@/model/Post"; export default function FollowingPosts() { const { isFetching, fetchNextPage, hasNextPage, data } = useSuspenseInfiniteQuery<IPost[], Object, InfiniteData<IPost[]>, [_1: string, _2: string], number>({ queryKey: ["posts", "followings"], queryFn: getFollowingPosts, initialPageParam: 0, getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => lastPage.at(-1)?.postId, }); const { ref, inView } = useInView({ threshold: 0, delay: 100, }); useEffect(() => { if (inView) !isFetching && hasNextPage && fetchNextPage(); }, [inView, fetchNextPage, hasNextPage, isFetching]); if (!data) return null; return ( <> {data.pages.map((ele: IPost[], idx: number) => ( <Fragment key={idx}> {ele.map((ele) => ( <Post key={ele.postId} post={ele}></Post> ))} </Fragment> ))} <div ref={ref} style={{ height: "100px" }}></div> </> ); }
- 해결됨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옵션을 주었는데 에러가 왜 뜨는지 궁금합니다.바쁘실텐데 많은 질문 죄송합니다 ㅜㅜ
- 해결됨Next + React Query로 SNS 서비스 만들기
서버 컴포넌트에서 server action 사용 질문이 있습니다.
서버 컴포넌트에서 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으로 잘 오는 것 같은데 리턴 메시지가 제대로 안되는 것인지 응답이 왜 없는 것인지 궁금합니다.