묻고 답해요
161만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결처음 만난 리액트(React)
useContext hook
useContext hook 을 사용할때 만약 랜더링이 무거운 작업이라면 최적화를 시켜줘야한다고 하셨는데 여기서 말하는 최적화란 무엇일까요? 변수에 담아서 데이터를 사용하는게 최적화 일까요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
CreateBoardComment
안녕하세요 createBoardComment 만들려고 mutation CreateBoardCommet doc을 보고 하고 있는데createBoardCommentInput과 boardId:ID! 를 두개다 써야되는데 어떻게 해야 되는지 알수 있을까요? 또한 밑에 createBoardComment도 필요하다 하는데 어떻게 써야되는건가요?감사합니다
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
안녕하세요 server에서 res.json과 res.send에 대해 궁금하네요
보통 항상 프론트엔드에 보낼때 res.json으로 보내었는데 이번에는 res.send를 사용 하였는데 2개가 차이가 있을까요?
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
Aws관련질문
강좌에서 aws 인스턴스를 2개를 사용해 프론트서버와 백엔드서버를 배포한것과는 다르게 프리티어 인스턴스 한개로 두개의 서버를 배포하려하는데 aws 서버 메모리가 부족할까요?
-
해결됨따라하며 배우는 리액트 테스트 [2023.11 업데이트]
This could be because the text is broken up by multiple elements. 에러
선생님 안녕하세요아무리 봐도 오류 이유를 모르겠어서 질문드립니다.제 오류는 아래와 같습니다. (코드상 에러난 부분 ✅ 했습니다)> TestingLibraryElementError: Unable to find an element with the text: /loading/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. // CompletePage.js import axios from "axios"; import React, { useEffect, useContext, useState } from "react"; import ErrorBanner from "../../components/ErrorBanner"; import { OrderContext } from "../../contexts/OrderContext"; function CompletePage({ setStep }) { const [OrderDatas, , resetOrderDatas] = useContext(OrderContext); const [orderHistory, setOrderHistory] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); useEffect(() => { orderCompleted(OrderDatas); }, [OrderDatas]); const orderCompleted = async (OrderDatas) => { try { let response = await axios.post( "http://localhost:5001/order", OrderDatas ); setOrderHistory(response.data); setLoading(false); } catch (error) { setError(true); } }; if (error) { return <ErrorBanner message="에러가 발생했습니다." />; } const orderTable = orderHistory.map((item) => ( <tr key={item.orderNumber}> <td>{item.orderNumber}</td> <td>{item.price}</td> </tr> )); const handleClick = () => { resetOrderDatas(); setStep(0); }; if (loading) { return <div>loading</div>; ✅ } else { return ( <div style={{ textAlign: "center" }}> <h2>주문이 성공했습니다.</h2> <h3>지금까지 모든 주문</h3> <table style={{ margin: "auto" }}> <thead> <tr> <th>주문 번호</th> <th>주문 가격</th> </tr> </thead> <tbody>{orderTable}</tbody> </table> <button onClick={handleClick}>첫페이지로</button> </div> ); } } export default CompletePage; //App.test.js import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import App from "./App"; test("From order to order completion", async () => { render(<App />); const event = userEvent.setup(); const americaInput = await screen.findByRole("spinbutton", { name: "America", }); await event.clear(americaInput); await event.type(americaInput, "2"); // England 여행 상품 3개 추가합니다. const englandInput = await screen.findByRole("spinbutton", { name: "England", }); await event.clear(englandInput); await event.type(englandInput, "3"); // insurance 옵션체크 const insuranceCheckbox = await screen.findByRole("checkbox", { name: "Insurance", }); await event.click(insuranceCheckbox); //모든 주문을 한 이후 주문 버튼 클릭! const orderButton = screen.getByRole("button", { name: "주문", }); await event.click(orderButton); ////////// 주문확인페이지 /////// const summaryHeading = screen.getByRole("heading", { name: "주문 확인" }); expect(summaryHeading).toBeInTheDocument(); const productHeading = screen.getByRole("heading", { name: "여행 상품: 5000", }); expect(productHeading).toBeInTheDocument(); const optionsHeading = screen.getByRole("heading", { name: "옵션: 500", }); expect(optionsHeading).toBeInTheDocument(); expect(screen.getByText("2 America")).toBeInTheDocument(); expect(screen.getByText("3 England")).toBeInTheDocument(); expect(screen.getByText("Insurance")).toBeInTheDocument(); const confirmCheckbox = screen.getByRole("checkbox", { name: "주문하려는것을 확인 하셨나요?", }); await event.click(confirmCheckbox); const confirmOrderButton = screen.getByRole("button", { name: "주문 확인", }); await event.click(confirmOrderButton); //// 주문 완료 //// const loading = screen.getByText(/loading/i); ✅ expect(loading).toBeInTheDocument(); const completeHeader = await screen.findByRole("heading", { name: "주문이 성공했습니다.", }); expect(completeHeader).toBeInTheDocument(); const loadingDisappeared = screen.queryByText("loading"); expect(loadingDisappeared).not.toBeInTheDocument(); const firstPageButton = screen.getByRole("button", { name: "첫페이지로", }); event.click(firstPageButton); const productsTotal = screen.getByText("상품 총 가격: 0"); expect(productsTotal).toBeInTheDocument(); const optionsTotal = screen.getByText("옵션 총 가격: 0"); expect(optionsTotal).toBeInTheDocument(); await waitFor(() => { screen.getByRole("spinbutton", { name: "America" }); }); }); 제가 에러를 이해한 바로는 return 문이 여러 경우로 나뉘어서 그렇다고 생각했습니다. 제대로 이해한게 맞을까요..?( This could be because the text is broken up by multiple elements.)실제로 아래 else return문에 loading을 넣어주니 해결이 되긴 했습니다. 하지만 아래 ✅와 같이 작성해주면 에러가 뜨네요..왜 이러는건지 혹시 아실까요? ㅠㅠif (loading) { return <div>loading</div>; ✅ } else { return ( <div style={{ textAlign: "center" }}> <h2>주문이 성공했습니다.</h2> <h3>지금까지 모든 주문</h3> <table style={{ margin: "auto" }}> <thead> <tr> <th>주문 번호</th> <th>주문 가격</th> </tr> </thead> <tbody>{orderTable}</tbody> </table> <button onClick={handleClick}>첫페이지로</button> </div> ); }선생님 코드를 보고 복붙했는데도 해결이 안되네요.ㅜ
-
미해결비전공자를 위한 진짜 입문 올인원 개발 부트캠프
"세팅 제이슨" 질문 보고왔는데 안되서 질문드립니다.
설정 창에 검색하니까 settings.json 이 안나오네요 ㅠㅠ 어떡하죠 편집이 안되네요 윈도우라 ctrl shift p 누르면 settings.json은 나와요
-
미해결Slack 클론 코딩[실시간 채팅 with React]
members 404 에러.. channels/undefined
안녕하세요.. 제가 members로 채널정보가 처음엔 제대로 불러와지는데 추후 일정한 간격으로 요청이다시 시작되고, 그 뒤로 404 에러가 뜹니다.. 코드를 보면서 문제점을 찾으려고 해보아도 되지않아서 글을 올립니다 ㅠㅠ..아직 채널 페이지를 완료하지 않아서 생긴 문제일껄까요..?https://github.com/nuring9/react-SWR-SlackClone_front제 깃허브 주소입니다..
-
해결됨[리뉴얼] React로 NodeBird SNS 만들기
안녕하세요.
안녕하세요.현재 새로 나온 노드 교과서 이북과 현영님께서 주신 현물 책도 가지고 있는 상황에서 공부를 시작하려고 하는데 강의 결제 후 같이 보는건 어떨까요??공부하는데 돈은 아끼면 안된다고 생각하는 편이라 학습 효율이 가장 중요합니다. 예전에 유튜브로 하나만 구매하면 된다곤 하셨는데 둘 다 병행하면서 보면 어떨지 궁금합니다. 그리고 만약 하나를 선택 한다면 책, 강좌 중 뭐가 더 괜찮을지 혹은 개인의 성향 차이일지도 궁금합니다.항상 좋은 강좌 감사합니다.
-
미해결프로젝트로 배우는 React.js
useParams 가 동작하지 않습니다.
안녕하세요.useParams 으로 파라미터 값을 보낸 뒤,console.log() 로 값을 출력해 보고 싶은데요.자꾸 undefined 만 출력 됩니다.대체 이유가 뭘까요??? ㅠㅠㅠㅠㅠㅠ// App.js import './App.css'; import { Routes, Route } from 'react-router-dom'; import Navbar from './components/Navbar'; import routes from './routes'; function App() { return ( <div> <Navbar></Navbar> <div className='container mt-3'> <Routes> {routes.map((item, i) => { return ( <Route path={item.path} element={item.component()} key={i} ></Route> ); })} </Routes> </div> </div> ); } export default App; // routes.js import HomePage from './pages/HomePage'; import ListPage from './pages/ListPage'; import CreatePage from './pages/CreatePage'; import EditPage from './pages/EditPage'; import ShowPage from './pages/ShowPage'; const routes = [ { path: '/', component: HomePage, }, { path: '/blog', component: ListPage, }, { path: '/blog/create', component: CreatePage, }, { path: '/blog/edit', component: EditPage, }, { path: '/blog/:id', component: ShowPage, }, ]; export default routes;// ShowPage.js import { useParams } from 'react-router-dom'; const ShowPage = () => { let { id } = useParams(); console.log(id); // undefined 출력 return <div>Show Pages</div>; }; export default ShowPage;
-
미해결따라하며 배우는 리액트, 파이어베이스 - 채팅 어플리케이션 만들기[2023.12 리뉴얼]
강의 도표 자료 다운을 받으면, zip파일에 아무것도 들어있지않다고 나옵니다.
윈도우 운영체제를 쓰는데 강의 도표 자료 다운을 받으면, zip파일에 아무것도 들어있지않다고 나옵니다.다시 강의 도표 자료를 올려주실 수 있을까요?
-
미해결따라하며 배우는 리액트 네이티브 기초
에뮬레이터를 찾을 수 없는 에러 (Android)
선생님 안녕하세요저의 경우에는 안드로이드를 사용해야하는 상황이어서 (사용 os window10)npm run android를 터미널에서 사용하는데요Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds와 같은 에러가 발생합니다프로젝트 생성이 익숙해지기 위해서 프로젝트 자체를 만드는걸 여러번 해봤는데요 생각보다 자주 발생하는 에러여서 이러한 에러를 어떻게 잡아낼 수 있는지 한번 질문드려봅니다
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
프론트에서 useSWR로 받아온 data 콘솔로그로
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 이걸 백엔드부분에서 콘솔로그를 출력안하고프론트에서 로그출력하는 법은 없을까요??백엔드에서말고 프론트에서도 받아온 데이터 보고싶은데 콘솔로그하면 데이터가 안뜨고, undefined만 떠서요..
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
수업질문 Unhandle Runtime Error해결 방법 문의드립니다.
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.인덱스와 유저페이지만 안들어가지고 다른 페이지들은 들어가집니다. 구글링 해봐도 해결을 못해서 질문남겨봅니다.혹시 어느 부분이 문제인지 알수 있을까요? 터미널 오류warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reloadstate { user: null, authenticated: false, loading: true }upstream image response failed for http://localhost:4000/images/qTXQHCjdvd.jpg 404ImageError: "url" parameter is valid but upstream response is invalid at imageOptimizer (/Users/camoma1/Desktop/reddit-clone-app/client/node_modules/next/dist/server/image-optimizer.js:476:19) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async cacheEntry.imageResponseCache.get.incrementalCache (/Users/camoma1/Desktop/reddit-clone-app/client/node_modules/next/dist/server/next-server.js:264:72) at async /Users/camoma1/Desktop/reddit-clone-app/client/node_modules/next/dist/server/response-cache/index.js:83:36 { statusCode: 404}런타임 에러Unhandled Runtime ErrorError: Image with src "http://localhost:4000/images/qTXQHCjdvd.jpg" is missing required "width" property.
-
미해결따라하며 배우는 리액트 네이티브 기초
에러 발생
ERROR Invariant Violation: "main" has not been registered. This can happen if: Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project. A module failed to load due to an error and AppRegistry.registerComponent wasn't called., js engine: hermes 위와같은 에러가 svg 관련 라이브러리 설치이후에 발생됩니다.. 검색을 여러방면해봤지만 답을찾지 못했습니다. { "name": "awesomeproject", "version": "1.0.0", "main": "node_modules/expo/AppEntry.js", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web" }, "dependencies": { "expo": "~48.0.6", "expo-status-bar": "~1.4.4", "react": "18.2.0", "react-native": "^0.71.3", "react-native-svg": "13.4.0", "svg": "^0.1.0" }, "devDependencies": { "@babel/core": "^7.20.0", "react-native-svg-transformer": "^1.0.0" }, "private": true }
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
Intersection observer에서
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.두 가지 질문이 있는데 답변해주시면 정말 감사드립니다.ㅠㅠㅠentrise[0] 이 뜻하는건 뭔지 알 수 있을 까요??아래에서 인수로 마지막 Post의 element를 설정했는데 그걸 의미하는건가요??위에서 setPage(page+1)을 하면 아래에서setPage가 +1이 돼서page가 +1이 되고, getkey의 pageIndex가 page값으로 돼서/posts?page=${pageIndex} 가 호출 되는 건가요??const page 가 getkey의 pageIndex인건가요??
-
해결됨따라하며 배우는 리액트 테스트 [2023.11 업데이트]
Type.test.js파일에 궁금한점이 생겼습니다
강사님 안녕하세요 ~~ 늘 잘 듣고 있습니다.복습을 하다 궁금한점이 생겼는데요!Type.test.js에서 Products컴포넌트의 img태그를 변수 productImages로 집어주신걸 보았습니다. 근데 img태그는 Type.js가 아닌 Products.js에 있는건데,그렇담 Products.test.js 파일을 따로만들어 테스트를 해야하는것이 아닌가 하는 궁금증이 생겼습니다.그냥 Type페이지에 Products 컴포넌트가 들어있기 때문에 Type.test.js에 사용한건가요?test("displays product images from server", async () => { render(<Type orderType="products" />); const productImages = await screen.findAllByRole("img", { name: /product$/i, }); expect(productImages).toHaveLength(2); const altText = productImages.map((element) => element.alt); expect(altText).toEqual(["America product", "England product"]); });
-
해결됨프론트엔드 개발자를 위한, 실전 웹 성능 최적화(feat. React) - Part. 1
lazy적용하였는데 네트워크탭에 분리하여 보이지 않습니다
안녕하세요,강의와 같이 lazy를 적용하였는데, 페이지 이동 후 네트워크 탭에서 새로 받는 청크파일이 표시되지 않는데 따로 설정이 필요한걸까요?코드import React, { Suspense, lazy } from 'react'; import { Switch, Route } from 'react-router-dom'; import './App.css'; const ListPage = lazy(() => import('./pages/ListPage/index')); const ViewPage = lazy(() => import('./pages/ViewPage/index')); function App() { return ( <div className="App"> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route path="/" component={ListPage} exact /> <Route path="/view/:id" component={ViewPage} exact /> </Switch> </Suspense> </div> ); } export default App; 네트워크 탭(전체로 선택하여 확인)게시글 목록 -> 상세로 페이지 이동후에 새로운 청크 받아지는 것이 보이질 않습니다 실행 환경OS: Mac OS크롬버전: 111개발툴: vscode
-
해결됨[리뉴얼] React로 NodeBird SNS 만들기
Credentials 설정 후 origin: true를 줘도 헤더 결과값이 안들어가요
안녕하세요!Credentials 설정 후 origin을 'http://localhost:3060' 으로도, true 로도 변경해봤지만 계속해서 해당 오류가 뜨는데 이유를 모르겠습니다. ㅠㅠ 제로초님의 오류와 다른 부분이 있는 것 같습니다.Access to XMLHttpRequest at 'http://localhost:3065/user/login' from origin 'http://localhost:3060' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.제 코드는 현재 이렇습니다.[app.js]const express = require("express"); const session = require("express-session"); const cookieParser = require("cookie-parser"); const cors = require("cors"); const passport = require("passport"); const dotenv = require("dotenv"); const postRouter = require("./routes/post"); const userRouter = require("./routes/user"); const db = require("./models"); const passportConfig = require("./passport"); const app = express(); dotenv.config(); passportConfig(); //서버 실행할 때 db sequelize 연결도 함께 실행 db.sequelize .sync() .then(() => { console.log("db 연결 성공"); }) .catch(console.error); // router보다 위에 작성해야 함 app.use( cors({ // origin: 'https://nodebird.com' // 설정된 웹페이지에서 오는 요청만 허용 // origin: "*" // 전체 허용 // origin: "http://localhost:3060", // withCredential: true 일 때 보안이 더 철저해져서 정확한 주소를 적어야 함 origin: true, // 요청을 보낸 곳의 주소가 자동으로 들어가 허용 credientials: true, }) ); // CORS 에러 처리법 2 (npm i cors) app.use(express.json()); // front에서 json형식으로 데이터를 보냈을 때 json형식의 데이터를 req.body로 넣어줌 app.use(express.urlencoded({ extended: true })); // form을 submit했을 때 urlencoded 방식으로 데이터가 넘어옴 app.use(cookieParser(process.env.COOKIE_SECRET)); app.use( session({ saveUninitialized: false, resave: false, secret: process.env.COOKIE_SECRET, }) ); app.use(passport.initialize()); app.use(passport.session()); app.get("/", (req, res) => { res.send("hello express"); }); app.get("/posts", (req, res) => { res.json([ { id: 1, content: "hello1" }, { id: 2, content: "hello2" }, { id: 3, content: "hello3" }, ]); }); app.use("/post", postRouter); app.use("/user", userRouter); app.listen(3065, () => { console.log("서버 실행중!!!!"); }); [sagas - index.js]import axios from "axios"; import { all, fork } from "redux-saga/effects"; // take 는 1회용이기 때문에 while(true) {} 문으로 감싸준다. 하지만 직관적이지 않으므로 take 대신에 takeEvery를 사용한다. // takeLatest 는 클릭이 두번되었을 때 두 번 실행되지 않기 위해 마지막 것만 실행되도록 하는 effect 이다. (요청은 취소되지 않고 응답만 취소되므로 서버에는 두개가 저장됨(치명적단점)) // takeLeading 은 첫번째 것만 실행되도록 하는 effect 이다. // throttle 은 시간제한을 두어 그 시간동안에 한번만 실행되도록 요청하는 것이다. (특수한 경우에 사용, 디도스 공격을 막을 때 좋음) import userSaga from "./user"; import postSaga from "./post"; axios.defaults.baseURL = "http://localhost:3065"; axios.defaults.withCredentials = true; // function* : generator 는 yield(중단점)가 있는 곳에서 멈춤 export default function* rootSaga() { // all 은 fork 나 call 을 동시에 실행시켜준다. yield all([ // fork !== call // fork 는 비동기 함수 호출 , call 은 동기 함수 호출 fork(userSaga), fork(postSaga), ]); } 어디서 잘못된 걸까요..? 오류를 보면 header in the response is '' 로 헤더의 결과 값이 없는 것같은데...origin 을 true 로 변경했는데 왜 안들어갈까요...
-
해결됨풀스택 리액트 라이브코딩 - 간단한 쇼핑몰 만들기
1일차 fetch api 진행 시 CORS 에러
1일차 fetch api 진행 시 CORS 에러가 발생합니다. node.js 와 express를 활용해서 프록시 서버를 만듦으로 해결할 수 있을 꺼같은데. 강의에서는 cors 에러가 발생하지 않은 것 같은데 왜 저만 발생하는 지 궁금합니다. 추가로 당연히 해결방안 또한 궁금합니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
HOC 강의 시청 후 응용? 질문
안녕하세요 멘토님.항상 좋은 강의 잘 보고 있습니다. HOC와 권한분기 실습 까지 수강을 마치고 궁금한 점이 생겨 질문 드립니다.페이지로 이동 시 HOC를 먼저 실행하여 로그인을 체크하는 방식은 이해했습니다.그런데, 간혹 어떤 특정 게시판 사이트에 비로그인 상태에서 댓글 작성을 한다고 가정할 때인풋창이나 등록 버튼을 누르면 '로그인 후 이용해주세요' 라는 알럿을 띄워주는 경우가 있습니다. (페이지 이동이 아닌 단순 엘리먼트 클릭)이러한 경우에는 그냥 단순히 인풋이나 등록 버튼 등 엘리먼트를 클릭 했을 때 토큰이 있는지 if 검증을 하는 로직만 넣으면 되는 것인지 궁금합니다.그리고 댓글 리스트 수정과 같은 상황에서 댓글 리스트에서 댓글 하나를 수정 버튼 눌렀을 때, 비로그인 유저를 감지하여 알럿을 띄워주고 싶은 경우도 궁금합니다. 이런 경우는 보통 이전 수업 때 배웠듯이 map을 사용하여 댓글 수정 컴포넌트를 반복문으로 뿌려주는 형태로 사용을 합니다. 그렇다면 이 댓글 수정 컴포넌트를 export 하는 과정에서 HOC를 씌워주는게 맞는 것인지, 아니면 그냥 또 단순히 수정 버튼 클릭 시 if 검증을 통해 토큰 존재 여부만 파악하면 되는지 궁금합니다. 감사합니다.