172만명의 커뮤니티!! 함께 토론해봐요.
미해결
Next + React Query로 SNS 서비스 만들기
안녕하세요 상세페이지에서 찜하기 요청을 하게되면 users/favorite/${peopleId}로 post 요청을 보내게되고 그럼 users/favorite api에 찜한 사람들의 목록이 추가됩니다. 찜하기를 눌렀을경우 아이콘의 컬러를 변경시켜야해서 getQueryData로 찜한 사람들의 목록 을 가져오려고 하였는데 const { data: likePeopleList } = useQuery<GetPeoples>({ queryKey: ["get", "likepeoples"], queryFn: getLikePeoples, staleTime: 60 * 1000, // fresh -> stale, 5분이라는 기준 gcTime: 300 * 1000, }); 위에 코드가 없으면 likeQuery를 가져오지 못하고있는것같습니다. getQueryData로 가져오는 방법이 잘못된걸까요? 다른 좋은 방법있다면 여쭤보고싶습니다. 밑에는 전체 코드입니다. type Props = { peopleId: string; }; export default function PeoplePosts({ peopleId }: Props) { const { data } = useQuery< GetPeoplePost, Object, GetPeoplePost, [_1: string, _2: string, _3: string] >({ queryKey: ["get", "peoplesDetail", peopleId], queryFn: getPeopleDetail, }); const { data: likePeopleList } = useQuery<GetPeoples>({ queryKey: ["get", "likepeoples"], queryFn: getLikePeoples, staleTime: 60 * 1000, // fresh -> stale, 5분이라는 기준 gcTime: 300 * 1000, }); const { content, nickname, userFileUrl, favoriteCount, viewCount, softSkill, techStack, links, position, alarmStatus, year, } = data?.data ?? {}; const queryClient = useQueryClient(); const likeQuery = queryClient.getQueryData<GetPeoples>([ "get", "likepeoples", ]); console.log("likeQuery", likeQuery); const liked = !!likeQuery?.data.find( (item) => item.userId === Number(peopleId), ); console.log("liked", liked); const like = useMutation({ mutationFn: (peopleId: string) => { return fetch( `${process.env.NEXT_PUBLIC_BASE_URL}/users/favorite/${peopleId}`, { method: "post", }, ); }, onMutate(peopleId: string) { const oldData = queryClient.getQueryData<GetPeoples>([ "get", "likepeoples", ]); if (oldData) { const newData = { ...oldData, data: oldData.data.map((item) => ({ ...item, userId: Number(peopleId), })), }; queryClient.setQueryData(["get", "likepeoples"], newData); } }, }); const unLike = useMutation({ mutationFn: (peopleId: string) => { return fetch( `${process.env.NEXT_PUBLIC_BASE_URL}/users/favorite/${peopleId}`, { method: "delete", }, ); }, onMutate(peopleId: string) { const oldData = queryClient.getQueryData<GetPeoples>([ "get", "likepeoples", ]); if (oldData) { const deleteData = { ...oldData, data: oldData.data.filter((item) => item.userId !== Number(peopleId)), }; queryClient.setQueryData(["get", "likepeoples"], deleteData); } }, }); const onLike: MouseEventHandler<HTMLButtonElement> = (e) => { e.preventDefault(); if (liked) { unLike.mutate(peopleId); } else { like.mutate(peopleId); } }; return ( <div className="flex flex-col"> <div className="flex flex-col gap-4 border-b pb-10"> <div className="flex items-center gap-[10px]"> <Image src={`${userFileUrl}`} alt="유저프로필" width={30} height={30} /> <h1 className="text-[32px] font-bold">{nickname}</h1> <div> <BlueTextBox textSize="12px" textToShow={`${position}`} /> </div> </div> <div className="flex flex-col gap-2"> {softSkill ?.split(",") .map((skill, i) => <HashTag text={skill} key={i} />)} </div> <div className="flex gap-3"> <HeartEyeIconBox count={favoriteCount as number} icon={heartIcon} /> <HeartEyeIconBox count={viewCount as number} icon={eyeIcon} /> </div> </div> <div className="mt-[42px] flex flex-col gap-[50px]"> <div className="people-post-grid"> <h1 className="text-[22px] font-bold">경력</h1> <h3>{year}</h3> </div> <div className="people-post-grid"> <h1 className="text-[22px] font-bold">사용언어</h1> <div className="flex gap-2"> {techStack ?.split(",") .map((stack, i) => ( <TechStack techStack={stack} showText key={`stack${i}`} /> ))} </div> </div> <div className="flex flex-col gap-3"> <h1 className="text-[22px] font-bold">자기소개</h1> <p>{content}</p> </div> <div className="flex flex-col gap-3"> <h1 className="text-[22px] font-bold">Link</h1> <Link href={links as string}>{links}</Link> </div> </div> <div className="mt-[60px] flex gap-[13px] self-center"> <button className={`h-[58px] w-[142px] rounded-md bg-neutral-orange-500 font-bold ${alarmStatus ? "text-neutral-white-0" : "text-neutral-black-800"}`} > {alarmStatus ? "제안하기" : "제안불가"} </button> <button onClick={onLike} className="flex h-[58px] w-[58px] flex-col items-center justify-center rounded-md border" > {liked ? ( <Image src={fillHeartIcon} alt="하트아이콘" width={20} height={20} /> ) : ( <Image src={heartIcon} alt="하트아이콘" width={20} height={20} /> )} <h5 className="text-[12px]">{favoriteCount}</h5> </button> </div> </div> ); }
react next.js react-query next-auth msw
2024-05-28T06:02:46.254Z
댓글 1
좋아요 0
조회수 225
미해결
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
geolocation부분에 const askForLocation = function () { navigator.geolocation.getCurrentPosition((position) => { console.log(position); }); }; askForLocation(); 이렇게 함수가 있는데 여기서 궁금한점이 askForLocation(); 함수 호출부분에 인자로 전달하는 것이 없는데 매개변수로 position에 위치정보 객체형식으로 콘솔에 나오는 이유가 뭔지 궁금합니다.
react node.js seo graphql next.js
부드러운 족제비
2024-05-28T02:56:50.340Z
댓글 3
좋아요 0
조회수 293
미해결
따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000 까지 하고 3000번 포트로 잘 들어가지는데 3000번포트를 지우고 들어가봐도 뒤에 :80을 붙여 넣어 들어가봐도 사이트에 연결할 수 없음이 뜨네요 왜 그럴까요??
react node.js postgresql docker typescript 클론코딩 next.js
2024-05-27T20:37:49.606Z
댓글 0
좋아요 1
조회수 315
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
함수, 변수의 호이스팅 강의 영상 부분에 if (storageData?.complete) { newLi.classList.add("complete"); } 이 코드에서 storageData 뒤에 ? 이 물으표가 없으면 매개변수를 받아오지 않게 되니 undefined라고 강사님이 말씀하시는데 이게 무슨 말인지 잘 모르겠습니다. 그리고 ToDoList에서 리스트에 추가를 하고 더블클릭 삭제, 전체 삭제까지는 어느정도 이해가 되는데 로컬스트리지 전체 부분이 조금 이해도 어려운데 어떻게 이해를 하면서 공부를 하면 좋을까요?
react node.js seo graphql next.js
부드러운 족제비
2024-05-27T12:31:16.791Z
댓글 2
좋아요 0
조회수 225
해결됨
Next + React Query로 SNS 서비스 만들기
Next.js와 Spring boot를 사용해서 소셜 로그인을 추가하려고 합니다. 소셜 로그인의 경우 코드와 토큰을 프론트에서 관리하지 않는 것이 좋다고 하여 백엔드에서 모든 로직을 처리하고 있습니다. 현재 프론트에서 window.location.href = "http://localhost:8080/oauth2/authorization/google"; 위와 같은 경로로 백엔드로 소셜 로그인 요청을 보내고 백엔드에서는 소셜 로그인을 진행한 뒤에 유저 정보를 생성하고 JWT를 생성한 뒤 응답의 헤더에 쿠키 형태로 JWT를 넣어 response.sendRedirect("http://localhost:3000/auth/social"); 로 리다이렉트하고 있습니다. 프론트에서는 /auth/social 페이지에서 쿠키에 있는 JWT를 꺼내 유저 정보를 가져오는 API를 다시 호출해 유저 정보를 가져오고 있습니다. 이 후 auth.js 라이브러리를 통한 session 관리를 하고자 하는데 session을 업데이트 하려면 어떻게 해야 하나요..? (session.user가 있는지 없는지를 통한 로그인 체크를 위해 사용한다고 이해했습니다.) 서버 컴포넌트에서 import { auth } from "@/auth"; 를 통해 가져온 session에 데이터를 넣어보았지만 데이터가 제대로 들어가지 않는 것 같아 조언을 구해봅니다..
react next.js react-query next-auth msw
이우열
2024-05-27T08:15:22.120Z
댓글 1
좋아요 0
조회수 889
미해결
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
현재 객체 localStorage저장 부분의 인강을 보다 궁금한점 있어 질문을 드립니다. const saveItemsFn = function () { const saveItems = []; for (let i = 0; i < todoList.children.length; i++) { const todoObj = { contents: todoList.children[i].querySelector("span").textContent, complete: todoList.children[i].classList.contains("complete"), }; saveItems.push(todoObj); } localStorage.setItem("saved-items", JSON.stringify(saveItems)); }; 현재 자바스크립트 코드 제일 마지막 부분에 saveItemsFn함수가 저장하는 부분이니 이 함수안에 localStorage.setItem을 사용해서 로컬스토리지에 저장을 하는것까지는 이해가 되었는데 저장된걸 가져오기 위해 const savedTodoList = localStorage.getItem("saved-items"); localStorage.getItem을 사용하는데 여기서 첫번째로 이 코드 위치가 다시 제일 위쪽에 작성이 되었는지 궁금하고 두번째로 이 코드가 saveItemsFn 함수 안에 작성이 되지 않은 이유는 getItem이 저장하는 코드가 아니기때문에 saveItemsFn안이 아닌 따로 다시 작성이 된것인가요?
react node.js seo graphql next.js
부드러운 족제비
2024-05-27T08:06:56.438Z
댓글 1
좋아요 0
조회수 166
미해결
따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
logout을 send하면 해당 오류가 발생합니다. 코드가 잘못된건지 궁금해 git 도 올려드립니다. 감사합니다. https://github.com/bukwon/boiler-plate
Kwon
2024-05-27T07:56:43.187Z
댓글 1
좋아요 0
조회수 344
해결됨
Next + React Query로 SNS 서비스 만들기
https://www.inflearn.com/questions/1268586/%EB%A1%9C%EA%B7%B8%EC%9D%B8-%EC%97%90%EB%9F%AC-%EC%A7%88%EB%AC%B8%EC%9E%85%EB%8B%88%EB%8B%A4 여기에서 질문했던 로그인 관련 문제입니다. 지금 현재 로그인 후 로그아웃 후 다른 아이디로 재로그인시에 로그아웃 버튼에 session정보가 제대로 안들어가는 것 같습니다. 처음 로그인 했을 때 로그아웃에 session 정보가 들어가고, 로그아웃 후 다른 아이디로 재로그인시에 로그아웃버튼에 로그아웃전의 계정의 정보가 들어가 있습니다. 백엔드 서버 콘솔에는 정보가 제대로 들어가 있지만, let session = await auth(); 에서 session정보가 제대로 안 받아지는건지, 아니면 캐싱된 정보가 계속 쓰이는 건지 모르겠지만, 정보가 제대로 안들어갑니다. 물론 새로고침시에 정상적으로 정보가 들어가집니다. 제 프로젝트에서 문제가 있는건가 싶어서, 코드를 비교해보고 next, next-auth 버전을 바꿔보기도 했지만, 해결이 안되어서, 배포된 https://z.nodebird.com/ 링크로도 해보았는데 똑같은 버그가 있는 것 같아서 질문드립니다. 무엇이 문제인지 궁금합니다. 좋은 하루 보내세요!
react next.js react-query next-auth msw
강주호
2024-05-27T06:57:14.736Z
댓글 2
좋아요 0
조회수 267
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
섹션 10에서 graphql codegen 설치하려는데요 강의에서는 yarn add -D @graphql-codegen/cli 을 설치하라고 하는데 지금 설치하려고 사이트에 들어가니 yarn add --dev typescript @graphql-codegen/cli 로 되어 있는데 같은 건가요? 그냥 아래 명령어 실행해도 되나요?
react node.js seo graphql next.js
베이직
2024-05-27T05:36:52.679Z
댓글 2
좋아요 0
조회수 252
해결됨
[React / VanillaJS] UI 요소 직접 만들기 Part 2
<div id='modalRoot' ref={ref} className='fixed inset-0 z-100 flex flex-col items-center justify-center' > {children} </div> 테일 윈드로 선생님 모달 포탈로만드는것 해보고있는데. 뒤에 클릭이 안되요 pointer-events-none 쓰지말고 하는법이 없을까요?! 일단은 아래처럼 쓰고잇긴한데 ㅠㅠ 먼가 ... 'use client'; import React, { useEffect, useRef } from 'react'; import { useModalStore } from '@/shared/models/modal/stores/modalStore'; const mutationObserverOption: MutationObserverInit = { childList: true, subtree: false, }; /** * 모달 컴포넌트를 렌더링하기 위한 전역 컨테이너 프로바이더입니다. * 모달이 열려 있을 때 body 요소에 'no-scroll' 클래스를 토글하여 스크롤을 비활성화합니다. * * @param {React.ReactNode} children - 모달 루트 내부에 렌더링할 자식 요소 * @returns {JSX.Element} 모달 루트 프로바이더 */ const ModalRootProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { const ref = useRef<HTMLDivElement>(null); const { openedModalTypes, closeModal } = useModalStore(); // const isModalOpen = openedModalTypes.length > 0; useEffect(() => { let observer: MutationObserver; /** * MutationObserver를 사용하여 모달 루트 컨테이너의 자식 요소 변경을 감지합니다. * 모달이 열려 있는 경우 body 요소에 'no-scroll' 클래스를 추가하고, 모달이 닫혀 있는 경우 클래스를 제거합니다. */ if (ref.current) { observer = new MutationObserver(() => { const size = ref.current?.childNodes.length || 0; document.body.classList.toggle('no-scroll', size > 0); ref.current!.classList.toggle('bg-black/50', size > 0); ref.current!.style.pointerEvents = size > 0 ? 'auto' : 'none'; }); observer.observe(ref.current, mutationObserverOption); } // 컴포넌트 언마운트 시 MutationObserver 연결을 해제합니다. return () => { observer.disconnect(); }; }, []); return ( <div id='modalRoot' ref={ref} className='fixed inset-0 z-100 flex flex-col items-center justify-center pointer-events-none' // onClick={handleOutsideClick} > {children} </div> ); }; export default ModalRootProvider;
react typescript dom ui vanilla-js
냠냠굿
2024-05-27T05:13:48.498Z
댓글 2
좋아요 1
조회수 328
미해결
Next + React Query로 SNS 서비스 만들기
선생님 안녕하세요 사이드플젝하면서 다시 보고있는데, 클라이언트 사이드에서 useSession데이터가 없어서 질문 드립니다. import NextAuth from "next-auth" import Credentials from "next-auth/providers/credentials" export const { handlers, signIn, signOut, auth } = NextAuth({ pages: { signIn: '/login', newUser: '/signup', }, providers: [ Credentials({ // You can specify which fields should be submitted, by adding keys to the `credentials` object. // e.g. domain, username, password, 2FA token, etc. credentials: { id: {}, password: {}, }, authorize: async (credentials) => { console.log(credentials, '-------------------credentials'); const authResponse = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/login`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(credentials), }) console.log(authResponse.ok, '-----------------------------authResponse.ok'); if (!authResponse.ok) { return null; } let user = await authResponse.json(); // return user object with the their profile data console.log(user, '--------------------------------'); return { id: user.id, email: user.id, name: user.nickname, image: user.image, ...user, } }, }), ], }) 먼저 auth.ts에서 유저 정보를 잘 받아와서 return해주는 것 확인하고, /profile/page.ts (서버클라이언트) /profile/_component/logoutButton (클라이언트 컴퍼넌트)에서 각각 세션을 확인해 봤습니다. (서버 컴포넌트) import { auth } from '@/auth'; const session = await auth(); console.log(session, '------------server side session'); if (!session?.user) { redirect('/login'); } (클라리언트 컴포넌트) 'use client'; import { Button } from '@/components/ui/button'; import { useCallback } from 'react'; // client component에서만! import { signOut, useSession } from 'next-auth/react'; import { useRouter } from 'next/navigation'; export default function LogoutButton() { const router = useRouter(); const { data: me } = useSession(); const onLogout = useCallback(() => { signOut({redirect: false}).then(() => {router.replace('/')}); }, [router]); console.log(me, '------------client side session'); if (!me?.user) return null; return ( <Button className='w-full' onClick={onLogout}>로그아웃</Button> ) } 결과로 와같이 클라리언트 사이드에서는 데이터가 없더라구요. 혹시 어떤부분을 좀 더 봐야할지 알 수 있을까요? 그리고 useSession을 호출하면서 Failed to load resource: the server responded with a status of 404 (Not Found) app-index.js:33 ClientFetchError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON at fetchData (client.js:49:22) at async getSession (react.js:109:21) at async __NEXTAUTH._getSession (react.js:270:43) session 404가 계속나오는데 제가 잘못 호출하고있는건지 궁금합니다.
react next.js react-query next-auth msw
챠챠_
2024-05-27T03:30:09.603Z
댓글 1
좋아요 0
조회수 456
미해결
실무에 바로 적용하는 프런트엔드 테스트 - 1부. 테스트 기초: 단위・통합 테스트
안녕하세요. 강의 내용 중 정확히 이해하지 못하고 있는 것이 있어서 질문 드립니다. 강의 중 로그인 버튼 같이 간단한 동작만 있는 컴포넌트는 그 자체를 테스트 하는 것이 아니라, 통합 테스트로 상태에 따른 동작을 검증하는 것이 더 효율적이고 정확한 테스트가 된다. 라고 하셨습니다. 또한 이런 컴포넌트는 스토리북과 같은 도구를 사용하여 스타일이나 레이아우싱 틀어지지 않는지 확인하는 것이 더 중요하다. 라고 말씀 하셨습니다. 이 뜻은 통합 테스트를 스토리북과 같은 도구와 함께 하라는 것이 아니라, 통합 테스트로 상태에 따른 동작을 검증하고, 그 안에 있는 각각의 컴포넌트들은 스토리북 안에서 스타일과 레이아웃이 틀어지지 않는지 확인하라는 것일까요? 아니면 스토리북을 통해 네비게이션 같은 컴포넌트를 만들고 그 단위로 통합 테스트를 하란 말씀이실까요?? 궁금합니다. 강의 너무 잘 듣고 있습니다. 정말 감사합니다!
javascript react 소프트웨어-테스트 vitest
Milkyway
2024-05-26T22:27:16.412Z
댓글 1
좋아요 0
조회수 205
미해결
파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)
db sqlite3 파일을 더블클릭했는데 3-4 2분10분 화면처럼 창이 안뜨는데 혹시 무엇이 잘못된지 알수있나요?>....
react python django web-api htmx
2024-05-26T13:43:58.501Z
댓글 1
좋아요 0
조회수 237
미해결
Next + React Query로 SNS 서비스 만들기
안녕하세요 선생님 강의보면서 플젝을 만들다가 여쭤보고 싶은게 생겼습니다. 📦(afterLogin) ┣ 📂(home) ┃ ┗ 📂_component ┃ ┃ ┣ 📜mbtiCarousel.module.css ┃ ┃ ┗ 📜MbtiCarousel.tsx ┣ 📂@modal ┃ ┣ 📂(.)promise ┃ ┃ ┗ 📂form ┃ ┃ ┃ ┗ 📜page.tsx ┃ ┣ 📂[userId] ┃ ┃ ┣ 📂_component ┃ ┃ ┃ ┗ 📜UsrCarousel.tsx ┃ ┃ ┗ 📜page.tsx ┃ ┗ 📜default.tsx ┣ 📂like ┃ ┗ 📜page.tsx ┣ 📂messages ┃ ┗ 📜page.tsx ┣ 📂profile ┃ ┗ 📜page.tsx ┣ 📂promise ┃ ┣ 📂form ┃ ┃ ┗ 📜page.tsx ┃ ┣ 📂_component ┃ ┃ ┣ 📜PromiseFormButton.tsx ┃ ┃ ┣ 📜promiseSection.module.css ┃ ┃ ┗ 📜PromiseSection.tsx ┃ ┗ 📜page.tsx ┣ 📂recommend ┃ ┣ 📂_component ┃ ┃ ┗ 📜RecommendSection.tsx ┃ ┣ 📜page.tsx ┃ ┗ 📜recommend.module.css ┣ 📂setting ┃ ┗ 📜page.tsx ┣ 📂[userId] ┃ ┗ 📜page.tsx ┣ 📂_component ┃ ┣ 📜Back.tsx ┃ ┣ 📜FriendRecommendSection.tsx ┃ ┣ 📜MainTitle.tsx ┃ ┣ 📜MbtiRecommendSection.tsx ┃ ┣ 📜Modal.tsx ┃ ┣ 📜userCard.module.css ┃ ┣ 📜UserCard.tsx ┃ ┗ 📜UserCardArticle.tsx ┣ 📜layout.module.css ┣ 📜layout.tsx ┗ 📜page.tsx 이런구조에서 (afterLogin) > UserCard 를 클릭하면 @modal > [userId] > page.tsx가 모달창으로 뜨게 됩니다. 새로고침해도 모달창이 뜨게 되어있습니다. 이게 로컬에서는 잘 작동하는데 테스트하려고 vercel에 배포해서 확인했더니 url은 바뀌는데 새로고침이 되고 화면은 바뀌지 않더라구요. 구글링해도 만족스런 답변이 없어서 이렇게 글을 남깁니다. return ( // <UserCardArticle user={user}> <Card className={style.userCard}> <Link href={`/${user.id}`} scroll={false} className='w-full h-full absolute top-0 left-0'> <img src={user.image[0]} className='rounded-xl h-full block w-full' alt="img" /> <div className={style.userInfo}> <h2 className='text-white font-extrabold text-xl'>{user.mbti.mbti}, 궁합 {user.mbti.score}%</h2> <h2 className='text-white font-extrabold text-xl'>{user.nickname}, {user.age}</h2> <p className='text-white font-semibold text-base'>{user.distance}km, {user.area}</p> </div> </Link> <div className='absolute bottom-3 px-3 w-full'> <Button variant={'default'} className='bg-white hover:bg-slate-50 w-full'> <UserPlus color='#000000' /> <span className='ml-2 text-black font-extrabold'>친구신청</span> </Button> </div> </Card> // </UserCardArticle> ) 기존 선생님처럼 UserCardArticle이란 컴포넌트를 만들어서 router.push도 해봤다가 link태그로 고쳐봤는데도 새로고침이 되어서 어떤부분을 봐야할지 조언 듣고 싶습니다. 감사합니다.
react next.js react-query next-auth msw
챠챠_
2024-05-26T04:08:18.012Z
댓글 1
좋아요 0
조회수 275
해결됨
실무에 바로 적용하는 스토리북과 UI 테스트
npm 배포이후 vite 를 사용하지않은 패키지에서 해당 DS npm 을 설치하고 사용하면 위와같은 오류가 나옵니다 먼가 강의대로 하면 Vite 로 이뤄진 패키지만 사용이 가능한걸까요
react typescript tailwind-css storybook ui-testing
roberto
2024-05-25T10:33:07.971Z
댓글 4
좋아요 3
조회수 679
해결됨
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
설치가 잘못된 걸까요.. yarn dev하니 오류가 납니다ㅜ
react node.js seo graphql next.js
leeyunje96
2024-05-24T19:40:53.591Z
댓글 1
좋아요 1
조회수 218
미해결
따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
강사님께서 mongoDB Clusters 카테고리 들어가면 데이터 확인하실 수 있는데, 저는 따로 뜨는게 없고 이런 화면이 나오네요. 어디서 볼 수 있나요?
Kwon
2024-05-24T08:07:43.179Z
댓글 1
좋아요 0
조회수 435
미해결
Next + React Query로 SNS 서비스 만들기
지금 로그인 후 핸들러에서 값을 잘 주는것을 확인했고 auth.ts의 콘솔 부분에 값이 잘 나오는것을 확인했습니다 여기서 result에서도 성공했다고 나오는데 replace가 안되네요 이유가 뭘까요
react next.js react-query next-auth msw
성민석
2024-05-24T07:53:48.978Z
댓글 2
좋아요 0
조회수 414
미해결
따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
안녕하세요. 현재 7강 듣고 있는데요, node.js run하고 postman에 이름, 이메일, 패스워드 넣어서 요청하면 에러 뜨고 종료가 됩니다... 이유가 뭔가요?
Kwon
2024-05-24T07:03:02.521Z
댓글 1
좋아요 0
조회수 302
미해결
코드로 배우는 React 19 with 스프링부트 API서버
import axios from "axios" import { API_SERVER_HOST } from "./todoApi" // api server host const host = `${API_SERVER_HOST}/api/products` // 외부 보낼것 만들기 비동기 통신 export const postAdd = async (product) => { // 객체지정 const header = {headers: {'Content-Type':'multipart/form-data'}} // product와 header 같이 보내기 const res = await axios.post(`${host}/`, product, header) return res.data } export const getList = async (pageParam) => { try{ const {page, size} = pageParam const res = await axios.get(`${host}/list`, {params: {page:page, size:size}}) return res.data } catch (error) { console.error('Error in getList:', error); throw error; } } productsApi.js 위 코드이고 import React, { useState, useEffect } from 'react'; import useCustomMove from '../../hooks/useCustomMove'; import { API_SERVER_HOST } from '../../api/todoApi'; import { getList } from '../../api/productsApi'; const initState = { dtoList: [], pageNumList: [], pageRequestDTO: null, prev: false, next: false, prevPage: 0, nextPage: 0, current: 0 } // 서버에 주소가 바뀌면 상수값만 바꿔줄려고 선언한것 const host = API_SERVER_HOST function ListComponent(props) { // 커스텀 훅 사용해서 이동 refresh: 갱신 const {moveToList, moveToRead, page, size, refresh} = useCustomMove() // 목록 데이터 가져오기 const [serverData, setServerData] = useState(initState) // 데이터 가져오기 const [fetching, setFetching] = useState(false) useEffect(() => { setFetching(true) // 데이터 가져오는 중 자동으로 처리되기 때문에 // 서버데이터가 처리가 되면 getList({page,size}).then(data => { console.log("data>>>>>>>", data); setFetching(false) setServerData(data) }) }, [page,size,refresh]); return ( <div className="border-2 border-blue-100 mt-10 mr-2 ml-2"> {/* fetching일때는 FetchingModal 호출하고 그렇지 않으면 아무것도 안보여준다. */} {fetching? <FetchingModal/> :<></>} <div className="flex flex-wrap mx-auto p-6"> {serverData.dtoList.map(product => <div key= {product.pno} className="w-1/2 p-1 rounded shadow-md border-2" onClick={() => moveToRead(product.pno)} /* 링크 만들어주고 썸네일 이미지 만들어서 보여주는 기능 */ > <div className="flex flex-col h-full"> <div className="font-extrabold text-2xl p-2 w-full ">{product.pno}</div> <div className="text-1xl m-1 p-2 w-full flex flex-col"> <div className="w-full overflow-hidden "> <img alt="product" className="m-auto rounded-md w-60" src={`${host}/api/products/view/s_${product.uploadFileNames[0]}`} /> </div> <div className="bottom-0 font-extrabold bg-white"> <div className="text-center p-1"> 이름: {product.pname} </div> <div className="text-center p-1"> 가격: {product.price} </div> </div> </div> </div> </div> )} </div> </div> ); } export default ListComponent; ListComponent.js 파일인데 import React from 'react'; import ListComponent from '../../components/products/ListComponent'; function ListPage(props) { return ( <div className="p-4 w-full bg-white"> <div className="text-3xl font-extrabold"> Products List Page </div> <ListComponent/> </div> ); } export default ListPage; ListPage.js 파일입니다 터미널에 에러도 뜨지 않고 서버에서 데이터를 못가져오는데 postman으로 서버 테스트를 했을때는 잘 되는데요 서버에서 클라이언트로 연동되는 부분에서 문제가 생긴건지 list를 가져오지를 못하고 있습니다 ㅠ 왜 그런건지 알 수 있을까요 ㅠ 오타도 아닌거 같고..
react spring-boot jpa jwt redux-toolkit
jkshin
2024-05-24T04:44:18.965Z
댓글 3
좋아요 0
조회수 317