묻고 답해요
121만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
질문있습니다
export const FETCH_BOARDS = gql` query fetchBoards($page: Int) { fetchBoards(page: $page) { _id writer title createdAt } } `; ($page:Int)와(page:$page)의 역할이 무엇인가요
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
로컬호스트 접속 시 Module not found: Can't resolve 'child_process' 에러
안녕하세요! 갑자기 로컬호스트에 접속이 안 되어서 질문합니다 npm run dev 하면 컴파일까지는 성공하는데 그 다음에 localhost로 접속하면 다음과 같은 에러가 뜹니다error - ./node_modules/worker-farm/lib/fork.js:3:0Module not found: Can't resolve 'child_process'nullError from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp'Could not find files for / in .next/build-manifest.json(중간중간에 콘솔로그 찍힌건 생략했습니다) 개발자도구 확인해보면 에러는 안 나옵니다구글링해서 package.json 수정하는 방법이랑 _document.js에 import 'classlist.js' 하는방법 시도해봤는데 오류가 해결되지 않았습니다.. 어떻게 해야할까요ㅠ
-
미해결[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
DB eaver 연결 오류
강의에 나온 백엔드 주소랑 강의 자료의 34.64.135.149 주소가 다릅니다 어떤 주소가 맞는지요? 둘 다 적용해도 접속이 안됩니다. 또한 port번호는 어떤 걸 사용해도 상관 없나요?
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
빌드 시간..
넥스트는 12버전 사용하고 있습니다.빌드 할 때 보통 시간이 20초 정도 걸리나요?새로고침하면 20초 정도 계속 걸려서 테스트하기가 참.. 힘드네용..ㅜ
-
해결됨만들면서 배우는 리액트 : 기초
강의 노트 위치를 모르겠습니다
커리큘럼 밑에 있다는데 어디 있는건가요....?? ㅠㅠㅠ
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
우분투 빌드 시간이 너무 깁니다.
ubuntu@ip-172-31-45-72:~/TwitterClone-FS-/front$ npm run build > react-nodebird-front@1.0.0 build > cross-env ANALYZE=true NODE_ENV=production next build Linting and checking validity of types .. ⨯ ESLint: ESLint configuration in .eslintrc is invalid: - Unexpected top-level property "parseOptions". ✓ Linting and checking validity of types Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc" https://nextjs.org/docs/messages/swc-disabled Webpack Bundle Analyzer saved report to /home/ubuntu/TwitterClone-FS-/front/.next/analyze/nodejs.html No bundles were parsed. Analyzer will show only original module sizes from stats file. Webpack Bundle Analyzer saved report to /home/ubuntu/TwitterClone-FS-/front/.next/analyze/edge.html Using external babel configuration from /home/ubuntu/TwitterClone-FS-/front/.babelrc ⚠ It looks like there is a custom Babel configuration can be removed : ⚠ Next.js supports the following features natively: ⚠ - 'styled-components' can be enabled via 'compiler.styledComponents' in 'next.config.js' ⚠ For more details configuration options, please refer https://nextjs.org/docs/architecture/nextjs-compiler#supported-features Creating an optimized production build ...계속 빌드를 진행하고있는데, ⨯ ESLint: ESLint configuration in .eslintrc is invalid: - Unexpected top-level property "parseOptions". 이부분, 통과못해도 계속해서 빌드가 진행되나요!? 아니면, 이부분때문에 지금 계속 빌드를 못하고 있는걸까요?평균적인 빌드시간을 알고 싶습니다.
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
ubuntu front 빌드 에러
ubuntu@ip-172-31-45-72:~/TwitterClone-FS-/front$ npm install npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '@faker-js/faker@8.3.1', npm WARN EBADENGINE required: { node: '^14.17.0 || ^16.13.0 || >=18.0.0', npm: '>=6.14.13' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: 'next@13.5.6', npm WARN EBADENGINE required: { node: '>=16.14.0' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: 'styled-components@6.1.1', npm WARN EBADENGINE required: { node: '>= 16' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } up to date, audited 421 packages in 3s 105 packages are looking for funding run `npm fund` for details 1 high severity vulnerability To address all issues (including breaking changes), run: npm audit fix --force Run `npm audit` for details. ubuntu@ip-172-31-45-72:~/TwitterClone-FS-/front$ npm run dev > react-nodebird-front@1.0.0 dev > next /home/ubuntu/TwitterClone-FS-/front/node_modules/next/dist/lib/picocolors.js:134 const { env, stdout } = ((_globalThis = globalThis) == null ? void 0 : _globalThis.process) ?? {}; ^ SyntaxError: Unexpected token '?' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at Module.mod.require (/home/ubuntu/TwitterClone-FS-/front/node_modules/next/dist/server/require-hook.js:64:28) at require (internal/modules/cjs/helpers.js:74:18) at Object.<anonymous> (/home/ubuntu/TwitterClone-FS-/front/node_modules/next/dist/build/output/log.js:55:21) at Module._compile (internal/modules/cjs/loader.js:999:30) ubuntu@ip-172-31-45-72:~/TwitterClone-FS-/front$ ls components next.config.js package-lock.json pages sagas utils hooks node_modules package.json reducers store ubuntu@ip-172-31-45-72:~/TwitterClone-FS-/front$ 이런 에러가 발생됩니다. unexpected token '?' 어떤 이유로 에러가 발생하고, 어떤식으로 해결해야지 실행할 수 있는지 알 고 싶습니다!!
-
미해결프로젝트로 배우는 React.js
useCallback 의존성 배열
const getPosts = useCallback((page = 1) => { let params = { _page: page, _limit: limit, _sort: 'id', _order: 'desc', title_like: searchText, } if (!isAdmin) { params = {...params, publish: true} } axios.get('http://localhost:3001/posts', { params }).then((res) => { setNumberOfPosts(res.headers['x-total-count']) setPosts(res.data); setLoading(false); }) },[isAdmin, searchText]) const onSearch = (e) => { if(e.key === 'Enter') { history.push(`${location.pathname}?page=1`) setCurrentPage(1); getPosts(1); } }getPosts 함수에 의존성 배열로 searchText가 들어가야 하는 이유는 뭔가요? 검색하려면 onSearch 함수가 실행될 때 getPost가 실행되는데 searchText 하나하나 바뀔 때마다 getPosts가 미리 새로 만들어질 필요는 없지 않나요?
-
해결됨Slack 클론 코딩[실시간 채팅 with React]
reactQuery로 짜고있는데...
useQuery 나 mutation같은걸 통해 데이터를 가져오는데 데이터 렌더링이랑 훅스랑겹치지않게 가장 함수끝부분에 배치해야된다해서 그렇게 배치했는데 data 의 null 값여부를 젤 밑에서 하니까 그위에 훅스들은 수동으로 null 값을 체크해야되는데 이런경우는 어떤식으로 하는게 좋을까요?interface Props { children?: React.ReactNode } const Comp: FC<Props> = () => { const {p1, p2} = useParams() if (!p1|| !p2) { return <>loading error</>; } const {data} = useQuery({ queryKey: mykey, queryFn: () => myfunc1(userId, codeId) }); const {mutate} = useMutation({ mutationFn: async (data: CodeRequestEntity) => { await myfunc2(data) return true } }) if(!data){ return <>loading</> } const onClickConfirm = useCallback(() => { mutate(data) onClose() }, []) return ( <> <Button variant={"outlined"} onClick={onClickConfirm}>예 </Button> </> ); }; export default Comp; 이런식으로 하게되면 분기문을통해 데이터 null 처리를 해서 분기문 밑어부터는 null 처리를 안해도되는데 null 처리를 가장 밑에 렌더링부분에 넣으면 그위에 훅스에선 데이터쓸때마다 null 처리해줘야되서 혹시 다른 방법 있을까요?
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
next-auth 로그인 시 unauthorized 문제
문제가 몇일째 안풀리는게 있어 문의드려요제가 next-auth를 사용해서 로그인 프로세스를 해보고 있습니다.로컬에서 별도로 배포환경 만들어서 테스트를 했을 때에는 잘 되는데 배포시에 계속 Unauthorized 에러가 발생해서요제가 작성한 [...nextauth].ts 코드입니다.import NextAuth, { User } from 'next-auth'; import CredentialsProvider from 'next-auth/providers/credentials'; import { refreshAccessToken } from 'utils/tokenRefresh'; export default NextAuth({ providers: [ CredentialsProvider({ name: 'Credentials', credentials: { userId: { label: 'UserId', type: 'text', placeholder: 'jsmith' }, password: { label: 'Password', type: 'password' }, }, authorize: async (credentials) => { const res = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/v1/users/signin`, { method: 'POST', body: JSON.stringify({ userId: credentials!.userId, password: credentials!.password, }), headers: { 'Content-Type': 'application/json' }, }); const user = await res.json(); // 로그인 성공 시 사용자 객체를 반환하고, 실패 시 null을 반환 if (res.ok && user) { console.log('ok user', user); return user; } else { console.log('error user', user); return false; } }, }), ], secret: process.env.NEXTAUTH_SECRET, // session: { // strategy: 'jwt', // maxAge: 0, // 브라우저가 닫히면 세션 종료 // // updateAge: 24 * 60 * 60, // 24시간마다 세션 갱신 (옵션) // }, callbacks: { async jwt({ token, user }) { // 사용자 로그인 시 토큰 설정 if (user) { return { ...token, accessJwt: user.result?.accessJwt, refreshJwt: user.result?.refreshJwt, companyId: user.result?.companyId, userName: user.result?.userName, accessTokenExpires: Date.now() + 3600 * 1000, }; } // 토큰 만료 확인 및 리프레시 if (Date.now() > token.accessTokenExpires!) { const newAccessJwt = await refreshAccessToken(token.refreshJwt!); return refreshAccessToken(newAccessJwt); } return token; }, async session({ session, token }) { if (token && token.accessJwt) { const customUser = session.user as User; if (!customUser.result) { customUser.result = { accessJwt: '', refreshJwt: '', companyId: '', userName: '', }; } customUser.result.accessJwt = token.accessJwt; customUser.result.refreshJwt = token.refreshJwt; customUser.result.companyId = token.companyId; customUser.result.userName = token.userName; session.user = customUser; } return session; }, }, }); NEXT_PUBLIC_BACKEND_URL 환경변수는 별도의 백엔드를 구성한 주소이구요 배포는 도커를 사용했습니다.FROM node:20.10 as builder # pnpm 설치 RUN npm install -g pnpm WORKDIR /usr/src/app COPY package*.json ./ RUN pnpm install ARG NEXT_PUBLIC_BACKEND_URL ARG NEXTAUTH_SECRET COPY . . RUN NEXT_PUBLIC_BACKEND_URL=https://${NEXT_PUBLIC_BACKEND_URL} NEXTAUTH_SECRET=${NEXTAUTH_SECRET} pnpm run build FROM node:20.10 RUN npm install -g pnpm WORKDIR /usr/src/app COPY --from=builder /usr/src/app/package*.json ./ RUN pnpm install --prod COPY --from=builder /usr/src/app . # COPY --from=builder /usr/src/app/.next ./.next EXPOSE 3000 CMD ["pnpm", "run", "dev"]NEXTAUTH_SECRET은 프론트 주소를 도커 실행 시 넣어줘야 한대서 도커 실행 할 때 환경변수로 따로 넣어줬구요Docs, Stackoverflow, ChatGPT 등 여러 방면으로 찾아봤는데 해결이 안되더라구요..강의하고는 별개 내용이긴 한데 더이상 물어볼 데가 없어서 강사님께 여쭈어봅니다..
-
미해결[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
Graphql 데이터 가지고 올때
이렇게 갈색으로 뜨는데, 에러가 되는 이유가 이 때문인 것 같아요. 무슨 이유 때문에 그럴까요? ㅠㅠㅠ
-
미해결[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
types.ts의 내용 중 누락된 게 많습니다
위는 선생님 파일 다운로드 한거의 package.json 이거는 제 포폴의 package.json 입니다ts-node 라든지 devDependencies에서도 빠진 게 몇개 있어보이는데.. 터미널에서 뭘 설치해야 할까요?? 수업 코드에서도 똑같이 설치한것같은데 types.ts 내용이 다르더라구요. ㅠㅠ이건 수업 코드 내의 package.json 입니다별 다를 건 없어 보입니다.. 근데 둘다 types.ts 내부 내용들이 누락된 게 너무 많더라구요 설치는 똑같이 한 거 같은데 버전 문제일까요?(types.ts)이런식으로 많이 다릅니다.. (오른쪽이 수업코드) +추가질문포트폴리오 파일인데 저런 오류가 뜹니다.. types.ts 에 누락된 내용이 많아서 그런걸까요?
-
미해결[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
마지막 페이지가 1000번대라 한참넘어가야되네요
다른 공부하시는분들도 잘 적용됐는지 확인하는데 번거로움이있을거 같아서 말씀드려요!
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
Graphql과 RestAPI
제가 리액트, node.js의 RestAPI를 다루는 부분이 필요해서 수업을 듣게 되었습니다.(전체적인 리액트, node.js의 활용법도 필요함) 그런데 Graphql이란 것이 있어서 그 부분을 뛰어넘고 제가 필요한 부분만 들으려고 하니까 섹션 8과 9가 Graphql을 모르면 진행이 안되는 것 같더라고요. 이런 경우 실무에서도 이런 식으로 많이 쓰시는지, 점점 바뀌는 추세인 건지 궁금합니다.
-
미해결[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
안녕하세요 질문있습니다!
안녕하세요 질문 있습니다!refetchQueries 적을 때 자동완성되는 익스텐션이 뭔지 알 수 있을까용?
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
Redux-Saga Login_REQUEST 문제입니다.
redux-saga 쪼개고 reducer 연결 하려고 하니 user reducer만 반응하고 LOG_IN_SUCCESS 는 반응을 하지 않습니다. 커뮤니티 게시판에서 여러가지를 확인해보고 해도 어디 부분이 잘못 된지 몰라 올려봅니다.. 제가 작성한 코드는 이러합니다. store/configureStore.js import { applyMiddleware, createStore, compose } from "redux"; import createSagaMiddleware from "redux-saga"; import { createWrapper } from "next-redux-wrapper"; import { composeWithDevTools } from "redux-devtools-extension"; import reducer from "../reducers"; import rootSaga from "../sagas"; const configureStore = (context) => { console.log("context", context); const sagaMiddleware = createSagaMiddleware(); const middlewares = [sagaMiddleware]; const enhancer = process.env.NODE_ENV === "production" ? compose(applyMiddleware(...middlewares)) // 배포용 : composeWithDevTools(applyMiddleware(...middlewares)); const store = createStore(reducer, enhancer); store.sagaTask = sagaMiddleware.run(rootSaga); return store; }; const wrapper = createWrapper(configureStore, { debug: process.env.NODE_ENV === "development", }); export default wrapper;reducers/index.js import { HYDRATE } from "next-redux-wrapper"; // HYDRATE = action import { combineReducers } from "redux"; import user from "./user"; import post from "./post"; const rootReducer = combineReducers({ index: (state = {}, action) => { switch (action.type) { case HYDRATE: console.log("HYDRATE", action); return { ...state, ...action.payload }; default: return state; } }, user, post, }); export default rootReducer; reducers/user.js export const initialState = { isLoggingIn: false, // 로그인 시도중 isLoggedIn: false, // 로그인 isLoggingOut: false, // 로그아웃 시도중 meUser: null, signUpData: {}, loginData: {}, }; export const LOG_IN_REQUEST = "LOG_IN_REQUEST"; export const LOG_IN_SUCCESS = "LOG_IN_SUCCESS"; export const LOG_IN_FAILURE = "LOG_IN_FAILURE"; export const LOG_OUT_REQUEST = "LOG_OUT_REQUEST"; export const LOG_OUT_SUCCESS = "LOG_OUT_SUCCESS"; export const LOG_OUT_FAILURE = "LOG_OUT_FAILURE"; export const loginRequestAction = (data) => ({ type: LOG_IN_REQUEST, value: data, }); export const logoutRequestAction = () => ({ type: LOG_OUT_REQUEST, }); const reducer = (state = initialState, action) => { // prettier-ignore switch(action.type) { case LOG_OUT_REQUEST : return {...state, isLoggingIn : true}; case LOG_IN_SUCCESS : return {...state, isLoggingIn : false, isLoggedIn:true, meUser:{...action.value, nickName:"Jay"}}; case LOG_IN_FAILURE : return {...state, isLoggingIn : false, isLoggedIn:false }; case "LOG_OUT_REQUEST" : return {...state, isLoggingOut:true}; case "LOG_OUT_SUCCESS" : return {...state, isLoggingOut:false, isLoggedIn:true, meUser:null}; case "LOG_OUT_FAILURE" : return {...state, isLoggingOut:false}; default: return state; } }; export default reducer;sagas/index.jsimport { all, fork, call } from "redux-saga/effects"; import userSaga from "./user"; export default function* rootSaga() { yield all([fork(userSaga)]); } sagas/user.js import { all, fork, put, delay, takeLatest } from "redux-saga/effects"; import { LOG_IN_FAILURE, LOG_IN_REQUEST, LOG_IN_SUCCESS, } from "../reducers/user"; function* logIn(action) { try { console.log("saga logIn"); // const result = yield call(logInAPI); yield delay(1000); yield put({ type: LOG_IN_SUCCESS, value: action.value, }); } catch (err) { console.error(err); yield put({ type: LOG_IN_FAILURE, error: err.response.data, }); } } function* watchLogIn() { yield takeLatest(LOG_IN_REQUEST, logIn); } function* watchLogOut() { yield takeLatest("LOG_OUT_REQUEST"); } export default function* userSaga() { yield all([fork(watchLogIn), fork(watchLogOut)]); }
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
evnet.target에 id 값이 없다 나오네요
event.target에 왜 id 가 없다 나오는지 알고 싶습니다
-
미해결한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
유데미 강의와 내용이 동일한가요??
유데미 강의와 동일한 버전인가요??
-
미해결한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
npx create-app reactexam1 에러
PS C:\reactexam1> npx create-react-app reactexam1npm ERR! code ENOENTnpm ERR! syscall lstatnpm ERR! path C:\Users\82108\AppData\Roaming\npmnpm ERR! errno -4058npm ERR! enoent ENOENT: no such file or directory, lstat 'C:\Users\82108\AppData\Roaming\npm'npm ERR! enoent This is related to npm not being able to find a file.npm ERR! enoentnpm ERR! A complete log of this run can be found in: C:\Users\82108\AppData\Local\npm-cache\_logs\2023-11-28T12_12_57_671Z-debug-0.log npx create-react-app reactexam1을 입력했을 때 계속 이런 에러가 뜹니다.폴더 위치를 c드라이브로 옮기는 것도 해보고 node.js를 다시 다운 받는 것도 해보았는데 계속해서 이런 에러가 발생합니다.
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
23분 13초 관련 질문입니다.
리트윗 에러시, alert를 띄워주실 때, 게시글 . 수만큼 리렌더링이 발생하셔서 index.js 상위 페이지로 에러를 올려주셨는데, 설명하실떄 리트윗 에러에다가, 게시글 id까지 같이 넣어서, 그. 포스트 카드에만 에러메시지가 나오게 해서 해결하실 수있다고 하셨습니다. 어떤식으로 코드를 작성하면 되는지 해당 부분에 대한 코드 작성법도 알고싶습니다.어떤식으로 postId를 넘겨주고 useEffect를 활용할 수 있는지 알고 싶습니다.function retweetAPI(data) { return axios.post(`/post/${data}/retweet`); } function* retweet(action) { try { const result = yield call(retweetAPI, action.data); yield put({ type: RETWEET_SUCCESS, data: result.data, }); } catch (err) { console.error(err); yield put({ type: RETWEET_FAILURE, error: err.response.data, }); } }