묻고 답해요
160만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결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 서비스 만들기
로그인을 서버액션으로 구현해봤는데 궁금한게 있습니다.
로그인을 클라이언트 컴포넌트에서 서버액션을 통해 구현해봤는데, 궁금한게 생겨서 질문 드립니다.로그인 모달의 코드입니다. "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으로 잘 오는 것 같은데 리턴 메시지가 제대로 안되는 것인지 응답이 왜 없는 것인지 궁금합니다.
-
해결됨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에 값이 안들어가는지 몇시간을 봐도 잘모르겠네요..ㅜㅜ
-
미해결Next + React Query로 SNS 서비스 만들기
NextAuth Credentials authorize의 결과 타입
return { name: user.nickname, email: user.email, image: user.profileImage, ...user, };강의에서 user를 그대로 리턴해서 사용하지 않고 user를 커스텀해준 것을 보았습니다. 현재 return하는 값은 Typescript에서 지정한 User 타입을 그대로 사용하면서 수정해서 값을 할당해줬다고 이해했는데 추가로 들어가는 ...user는 어디에서 사용할 수 있는지 궁금합니다. 추가로 제 코드에는 반환하는 정보가 더 많은데 어떤 식으로 값을 할당해서 사용할 수 있는지 궁금합니다.타입을 하나 만들어서 확장해서 사용하고 싶은데 따로 파일을 만들어줘야 할까요?
-
미해결Next + React Query로 SNS 서비스 만들기
Nextjs fetch, react-query 캐시 개념
Nextjs fetch도 캐시가 지원되고, react-query도 캐시가 지원되는걸로 이해를 했는데요 문득 궁금한 점이 생겨서 질문 드립니다. Nextjs fetch와 react-query에서의 캐시는 같은 개념인가요? 아니면 서로 다른 개념인가요?왜 Nextjs fetch를 안 쓰고 react-query를 쓰는 걸까요?Nextjs fetch는 어떨 때 쓰고 react-query는 어떨 때 쓰는 건가요?감사합니다.
-
해결됨Next + React Query로 SNS 서비스 만들기
Suspense 컴포넌트의 fallback 요소로 클라이언트 컴포넌트 전달?
안녕하세요.Suspense 컴포넌트의 fallback 요소로 서버 컴포넌트 전달은 문제가 없는데, 내부적으로 useEffect와 타이머를 사용하는 클라이언트 컴포넌트를 전달했더니 해당 훅과 관련된 내용은 모두 스킵되고 그냥 초기 렌더링 내용만 나오는 것 같은데, 애초에 클라이언트 컴포넌트는 전달이 불가능한걸까요?클라이언트 컴포넌트 사용 의도는 1초마다 로딩바 게이지가 증가하는 모습을 보여주고 싶어서 사용해보려고 했습니다.공식 문서를 봐도 해당 내용에 대해서는 언급이 없는 것 같습니다.감사합니다.
-
미해결Next + React Query로 SNS 서비스 만들기
useQuery 오류가 발생합니다
"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는 잘 작동합니다
-
미해결Next + React Query로 SNS 서비스 만들기
하이드레이션 에러
Unhandled Runtime ErrorError: 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를 눌러도 트윗이 변하지 않습니다 혹시 위 에러와 관련이 있나요?
-
미해결Next + React Query로 SNS 서비스 만들기
폴더 변경 이후 not found
패러렐 라우트 강의 중 폴더 이동하는 부분이 있는데i/flow/signup 페이지가 notFound로 나옵니다http://localhost:3000/ 경로에서도 해당 페이지 ui 가 나오지 않는데 어떤 문제일까요
-
미해결Next + React Query로 SNS 서비스 만들기
html a태그에 이미지를 표시하는 것은 웹 접근성 기준으로 올바른 것인지에 대한 질문입니다.
이번 강의에서 이미지 1장을 띄울때는 <img> 태그를 사용하셨습니다. 반면, 두 장 이상 이미지를 표시할 때에는 <Link> 컴포넌트 태그에 background-image 속성을 사용하여 이미지를 표시하셨는데, 혹시 제가 모르는 이점이 있는 것인지 궁금하여 질문 남기게 되었습니다.
-
미해결Next + React Query로 SNS 서비스 만들기
optimistic update 는 next 13 버전에서는 사용불가한가요?
현재 개발하는 환경이 13 버전인데임포트가 되지 않네요
-
해결됨Next + React Query로 SNS 서비스 만들기
2:56 src/app/page.tsx 파일을 이동 후 not-found 페이지만 뜹니다.
다른 분 질문 내용과 강의에 따르면 (beforeLogin)으로 옮겨진 page.tsx가 잘 떠야 하는데 저는 not-found.tsx만 뜨네요.왜 이러는지 제가 뭘 놓친건지 살펴보고 있는데 아직 못찾았습니다.. ( 혹시 저와 같은 경험이 있으신 분 / 해결하신 분 계신가요? )
-
해결됨Next + React Query로 SNS 서비스 만들기
"Validation failed (numeric string is expected)" 400 에러와 함께 유저 프로필 / 게시글을 불러오지 못합니다
해당 오류와 함께 유저 프로필 페이지 접속시 게시글을 불러오지 못합니다...!! 콘솔창에서는 해당 메시지와 함께 오류가 출력되는데 맨 밑에 d는 UserPosts.tsx 컴포넌트에서 찍어본 useQuery로 패칭한 데이터 찍어본것 입니다. getUserPosts.ts에서 받아온 res 값을 콘솔에 찍어봤습니다제로초님 코드와 동일한데 어떤 이유에선지 유저 프로필 페이지 게시글을 못불러오는지 잘 모르겠어서 낑낑대다가 질문 드렸습니다...ㅠㅠ 감사합니다
-
미해결Next + React Query로 SNS 서비스 만들기
포토 모달의 인터셉팅 라우터
안녕하세요, 제로초님.사진 크게보기 modal을 보던 중 궁금한게 있어서 질문 드립니다.사진을 크게 보기 위해 페러렐 라우터와 인터셉팅 라우터를 사용한다고 하셨는데인터셉팅 라우터를 사용하기 위해선@modal/[username]이 아니라@modal/(.)[username] 이 되어야 하는게 아닌지 질문 드려요! 뿐만 아니라 위에 같이 (.)을 붙이지 않았을 경우에 http://localhost:3000/elonmusk/status/1/photo/1위 URL에서 새로고침을 하게되면인터셉팅 되지 않은(afterLogin)/[username]/status/[id]/photo/[photoId]/page.tsx가 나타나야 하고 이는 Home 화면을 보여주기로 하였는데이 부분도 동작하고 있는 것 같지 않습니다. 혹시 원래 동작하는데 제가 놓친 부분이 있는걸까요?
-
미해결Next + React Query로 SNS 서비스 만들기
Next.js에 Custom hook 디자인 패턴을 사용하는 것에 대해 어떻게 생각하시나요?!
안녕하세요 !Next.js에 Custom hook 디자인 패턴을 사용하는 것에 대해 어떻게 생각하시나요 ?!hooks 폴더를 페이지 단위로 두어 RCC 컴포넌트 내부 로직을 hooks으로 관리하는 Custom hook 패턴과 아토믹을 함께 사용하려고 하고 RSC 컴포넌트에서는 아토믹 패턴을 사용하려고 하는데 이렇게 hooks을 next에서 사용해도 괜찮은 건지 고민이 들어서 질문 드립니다 ! (정답이 없는 문제인 건 알지만 어떻게 생각하시는지 궁금하여 질문드립니다.)
-
미해결Next + React Query로 SNS 서비스 만들기
GET 오류
dependencies에 next-auth버전입니다"next-auth": "^4.24.7",오류를 보면 import NextAuth from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; import { NextResponse } from "next/server"; export const { handlers: { GET, POST }, auth, signIn, } = NextAuth({ pages: { signIn: "/i/flow/login", newUser: "/i/flow/signup", }, providers: [ CredentialsProvider({ async authorize(credentials) { const authResponse = await fetch( `${process.env.NEXT_PUBLIC_BASE_URL}}/api/login`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ id: credentials.username, password: credentials.password, }), } ); if (!authResponse.ok) { return null; } const user = await authResponse.json(); console.log("user", user); return { email: user.id, name: user.nickname, image: user.image, ...user, }; }, }), ], }); 이게 제 코드인데 제 코드에서는 credentials 속성이 없다고 뜨는데실행해보면Unhandled Runtime ErrorError: Cannot read properties of undefined (reading 'GET')Sourcesrc/auth.ts (6:14) @ GET 4 | 5 | export const { > 6 | handlers: { GET, POST }, | ^회원가입시 이런 오류가 뜹니다오류와 대조를 하여 공식문서를 보면현재 여기 credentials의 코드가 바뀐것같은데제 코드에서 어떻게 수정을 해줘야할지 모르겠습니다.vscode자체 오류로도credentials' 속성이 '{ authorize(credentials: Record | undefined): Promise; }' 형식에 없지만 'Pick>, "credentials" | "authorize"> 형식에서 필수입니다.라고 뜨는것으로 보아 제 생각에도 공식문서에있는 credentials 속성을 넣어줘야하는것같은데 어떤식으로 해야할지 잘 모르겠습니다.route.ts 역시// api auth와 관련된 주소는 전부 nextauth가 관리 export { GET, POST } from "@/auth"; 이런식으로 잘 넣어주었구요.어떤식으로 수정을해야 GET오류가 나지 않을까요 ?
-
미해결Next + React Query로 SNS 서비스 만들기
context provider에 관한 질문
Tab.tsx에서 "추천"과 "팔로우 중"을 클릭하면 상태가 "rec", "fol"로 변경되는 것을 확인했습니다. 이후 TabProvider.tsx 파일을 만들고 <TabProvider>로 상태를 공유할 하위 컴포넌트를 감싸는 것 까지 되었습니다. TabProvider.tsx에 있는 state를 하위 컴포넌트가 구독하여 상태 공유를 할 수 있는 것으로 알고있습니다.여기서 질문입니다.TabProvider.tsx로 감싼 하위 컴포넌트인 Tab.tsx에서 상태가 변경되었을 때, TabProvider에 변경된 상태를 공유할 수 있는지 궁금합니다. (자식 컴포넌트에서 상태가 변경되면, Provider 상태도 변경할 수 있는지) Post.tsx에서 상태공유 확인하는데, Tab.tsx에서 상태가 변경되어도 Provider에서는 변경되지 않아 질문 올립니다.. import { TabContext } from "../home/_component/TabProvider"; const Post = () => { const { tab } = useContext(TabContext); return ( <> <div>TabContext Value = {tab}</div> </> ); };
-
미해결Next + React Query로 SNS 서비스 만들기
leftSectionWrapper와 rightSectionWrapper 중앙 정렬 방법에 관하여
양 사이드에 flex-grow : 1; 씩 주는 방법을 처음 알게되었습니다. 이전에는 현재 구현하고자 하는 레이아웃처럼 중앙정렬 할 때, 아래 코드처럼 요소 전체를 감싸는 컨테이너에 justify-content : center;를 지정해서 정렬했었습니다. (아래 코드 첨부)레이아웃을 정확하게 중앙에 놔둘 때에는 flex-grow 및 justify-content를 선택해서 사용할 수 있을 것 같고, flex-grow는 비대칭적인 레이아웃을 구성할 때, 더 유용할 수 있겠다. 라고 생각하는데 올바른 접근일까요??.container { display: flex; align-items: stretch; background-color: #fff; justify-content: center; }