inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

172만명의 커뮤니티!! 함께 토론해봐요.

우분투 빌드 시간이 너무 깁니다.

미해결

[리뉴얼] 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
  • redux
  • node.js
  • express
  • next.js
김용민 댓글 2 좋아요 0 조회수 478

ubuntu front 빌드 에러

미해결

[리뉴얼] React로 NodeBird SNS 만들기

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
  • redux
  • node.js
  • express
  • next.js
김용민 댓글 1 좋아요 0 조회수 1109

next-auth 로그인 시 unauthorized 문제

미해결

[리뉴얼] React로 NodeBird SNS 만들기

문제가 몇일째 안풀리는게 있어 문의드려요 제가 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 등 여러 방면으로 찾아봤는데 해결이 안되더라구요.. 강의하고는 별개 내용이긴 한데 더이상 물어볼 데가 없어서 강사님께 여쭈어봅니다..

  • react
  • redux
  • node.js
  • express
  • next.js
  • next-auth
  • docker
댓글 2 좋아요 0 조회수 773

Graphql 데이터 가지고 올때

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

이렇게 갈색으로 뜨는데, 에러가 되는 이유가 이 때문인 것 같아요. 무슨 이유 때문에 그럴까요? ㅠㅠㅠ

  • react
  • node.js
  • seo
  • graphql
  • next.js
uri 댓글 1 좋아요 0 조회수 380

types.ts의 내용 중 누락된 게 많습니다

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

위는 선생님 파일 다운로드 한거의 package.json 이거는 제 포폴 의 package.json 입니다 ts-node 라든지 devDependencies에서도 빠진 게 몇개 있어보이는데.. 터미널에서 뭘 설치해야 할까요?? 수업 코드에서도 똑같이 설치한것같은데 types.ts 내용이 다르더라구요. ㅠㅠ 이건 수업 코드 내의 package.json 입니다 별 다를 건 없어 보입니다.. 근데 둘다 types.ts 내부 내용들이 누락된 게 너무 많더라구요 설치는 똑같이 한 거 같은데 버전 문제일까요? (types.ts) 이런식으로 많이 다릅니다.. (오른쪽이 수업코드) +추가질문 포트폴리오 파일인데 저런 오류가 뜹니다.. types.ts 에 누락된 내용이 많아서 그런걸까요?

  • react
  • node.js
  • seo
  • graphql
  • next.js
nyang 댓글 2 좋아요 0 조회수 452

'[섹션 8. Connection & Hook] Postgres 컨테이너 올리기' 강의에서 sudo docker compose up 명령어가 제대로 실행되지 않습니다.

미해결

Airflow 마스터 클래스

이전까지는 도커 서비스를 잘 수행이 됐었습니다. 이번 강의에서 docker-compose.yaml파일을 수정 후 서비스를 내렸다가 다시 올리려고 하니 사진처럼 해당 로그까지만 찍힌 후에 더 이상 진행이 되지 않고 있습니다. 계속 기다려봐도 상태가 그대로인 것을 보아하니 어딘가 문제가 생긴 것 같습니다. yaml파일은 올려주신 파일과 비교해봤을 때 오타나 다른 문제는 없는 것 같습니다. 원래의 docker-compose.yaml로 교체하면 잘 실행이 되는 상태입니다. 뭐가 문제일까요?

  • python
  • 데이터-엔지니어링
  • airflow
재윤 댓글 2 좋아요 0 조회수 464

마지막 페이지가 1000번대라 한참넘어가야되네요

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

다른 공부하시는분들도 잘 적용됐는지 확인하는데 번거로움이 있을거 같아서 말씀드려요!

  • react
  • node.js
  • seo
  • graphql
  • next.js
손성오 댓글 2 좋아요 0 조회수 209

Graphql과 RestAPI

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

제가 리액트, node.js의 RestAPI를 다루는 부분이 필요해서 수업을 듣게 되었습니다. (전체적인 리액트, node.js의 활용법도 필요함) 그런데 Graphql이란 것이 있어서 그 부분을 뛰어넘고 제가 필요한 부분만 들으려고 하니까 섹션 8과 9가 Graphql을 모르면 진행이 안되는 것 같더라고요. 이런 경우 실무에서도 이런 식으로 많이 쓰시는지, 점점 바뀌는 추세인 건지 궁금합니다.

  • react
  • node.js
  • seo
  • graphql
  • next.js
uri 댓글 2 좋아요 0 조회수 336

안녕하세요 질문있습니다!

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

안녕하세요 질문 있습니다! refetchQueries 적을 때 자동완성되는 익스텐션이 뭔지 알 수 있을까용?

  • react
  • node.js
  • seo
  • graphql
  • next.js
yoonseong 댓글 2 좋아요 1 조회수 243

Redux-Saga Login_REQUEST 문제입니다.

미해결

[리뉴얼] React로 NodeBird SNS 만들기

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.js import { 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)]); }

  • react
  • redux
  • node.js
  • express
  • next.js
jaeyong Kim 댓글 2 좋아요 0 조회수 496

evnet.target에 id 값이 없다 나오네요

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

event.target 에 왜 id 가 없다 나오는지 알고 싶습니다

  • react
  • node.js
  • seo
  • graphql
  • next.js
손성오 댓글 1 좋아요 0 조회수 417

23분 13초 관련 질문입니다.

미해결

[리뉴얼] React로 NodeBird SNS 만들기

리트윗 에러시, 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, }); } }

  • react
  • redux
  • node.js
  • express
  • next.js
김용민 댓글 1 좋아요 0 조회수 280

wilcoxon 검정에 대한 질문입니다!

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

이전 단일 표본 검정에서 정규성 검증을 진행할 때 willcoxon 코드를 알려주실 때stats.wilcoxon(df[’무게‘]-120, alternative=’less’)와 같이 알려주셨는데 이번 대응표본 검정에서 정규성 검증을 진행할 때 willcoxon는 stats.wilcoxon(df[‘after’] ,df[‘before’], alternative = ‘greater’)와 같이 알려주셨습니다.또한 강의에서도 after와 before의 값을 빼서 넣은 값인 df['diff']를 그대로 사용해도 된다고 말씀하셨습니다.그래서 아래 사진과 같이 임의로 df[‘after’] - df[‘before’]를 넣어서 실행해봤는데 결과값이 똑같이 나왔습니다. 그럼 단일 표본 검정에서 알려주신대로 df[’무게‘]-120와 같이 df[‘after’] - df[‘before’]로 생각하고 넣어줘도 무방한 것인가요?

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
김건우 댓글 1 좋아요 0 조회수 314

섹션 13. 타입스크립트 설치 이슈

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

섹션 13의 본문 파트는 잘 따라 갔는데 혼자 freeboard에 진행하려 하니 계속 오류가 나네요.. 답변주신대로 설치 명령어의 오타를 수정해서 yarn add -D @graphql-codegen/typescript로 한 뒤 yarn generate를 실행하니 type.ts 이 안생기고 error Command failed with exit code 127. 라는 에러가 발생하네요ㅠㅠ 설치 파트에서 계속 막히니 힘드네요.. 확인 한번 해주실 수 있으실까요?

  • react
  • node.js
  • seo
  • graphql
  • next.js
서나현 댓글 1 좋아요 0 조회수 290

next 13,14버전으로 하고 있는데 antd에서 다음과같은 오류가 발생합니다.

미해결

[리뉴얼] React로 NodeBird SNS 만들기

SyntaxError: Cannot use import statement outside a module 이란 에러가 발생하는데 왜그런걸까요 stackoverflow찾다보니 nextjs 바벨설정이 src 하위를 보게되있어서 es6문법을 변환못해준다고 next.config.js 파일에 아래 transpilePackages 설정을 저렇게 넣어주면 해당 오류가 사라지긴하는대 매번 이렇게 해야되는건지... 근본적인 해결하려면 어떻게 해야할까요 const nextConfig = { reactStrictMode: true, transpilePackages: [ 'antd', '@ant-design', 'rc-util', 'kitchen-flow-editor', '@ant-design/pro-editor', 'zustand', 'leva', 'rc-pagination', 'rc-picker', 'rc-notification', 'rc-tooltip' ], }

  • react
  • redux
  • node.js
  • express
  • next.js
황영롱 댓글 1 좋아요 1 조회수 1204

4-2 type 1 4 번 문제

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

형별로 합하기 위해 df = df.T 를 쓰셨는데 print(sum(df.sum(axis=1) > 3000)) 를 쓰면 안 될까요 ? 해보니 답은 동일 했습니다.

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
paul1142 댓글 3 좋아요 1 조회수 400

styles.js 자동완성이 안되요

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

styles.js 자동완성이 안되는데 익스텐션 뭐 설치해야되나요?

  • react
  • node.js
  • seo
  • graphql
  • next.js
yoonseong 댓글 1 좋아요 1 조회수 384

캐러셀 arrow 위치 질문

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

다음 부분과 같이 아주 작게 이상한 위치에 나오는데 이를 옮기는 방법을 알고 싶습니다

  • react
  • node.js
  • seo
  • graphql
  • next.js
손성오 댓글 1 좋아요 0 조회수 378

훈훈한 자바스크립트_eventListener를 활용한 태그 삭제

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

아래코드를 입력했는데, newLi dblclick했을때 삭제처리가 되지 않습니다. 문제가 뭘까요? const todoInput = document.querySelector("#todo-input"); const createTodo = function () { const todoList = document.querySelector("#todo-list"); //List자체를 받아오기 const newLi = document.createElement("li"); const newSpan = document.createElement("span"); /** * pseudo: (addEventListner) * 할일이 완료가 된지 안된 일인지 알 수가 없음 -> EventListner를 추가 * 버튼태그와 함께 온클릭 이벤트를 생성 */ //02-addEventListner파트: 버튼태그 추가 및 Event속성(onClick 추가) const newBtn = document.createElement("button"); newBtn.addEventListener("click", () => { //클릭을 했을 때 어떻게 할지에 대한 내용을 익명 함수로 지정 newLi.classList.toggle("complete"); //버튼을 눌렀을 때 새로운 클래스를 추가해준다 }); //02-addEventListner: 당연히 삭제도 되어야할텐데... (더블클릭 -> 삭제) newLi.addEventListener("dblclick", () => { newLi.remove(); }); newSpan.textContent = todoInput.value; newLi.append(newBtn); newLi.appendChild(newSpan); todoList.appendChild(newLi); //왜 굳이 span태그를 만들고 span 태그를 List에 추가한 건지는 알 수가 없으나.. 나중에 알려주겠지.. todoInput.value = " "; console.log(newLi); }; //여기까지만 했을때는 기능상 부족한 부분이 상당히 많음 const keyCodeCheck = function () { if (window.event.keyCode === 13 && todoInput.value) { //만약 키보드값에 대해 enter값이 눌리면 -> createTodo(); } };

  • react
  • node.js
  • seo
  • graphql
  • next.js
nazombwa 댓글 1 좋아요 0 조회수 246

'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다 오류 질문

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

안녕하세요 과제 중 궁금한 점이 있어 질문 남깁니다 pages - index 파일 export default function DetailBoardPage(): JSX.Element { return ( <> <DetailBoard></DetailBoard> <CommentWrite></CommentWrite> <CommentList></CommentList> </> ); } board list presenter 파일 export default function CommentListItemUI( props: ICommentListItemUI ): JSX.Element { // 수정 아이콘 클릭 시 수정 화면으로 전환 const [isEdit, setIsEdit] = useState(false); const onClickUpdateIcon = (): void => { setIsEdit(true); return ( <> {!isEdit && ( . . . )} {isEdit && ( <CommentWrite item={props.item} isEdit={true} setIsEdit={setIsEdit} ></CommentWrite> )} </> ); } CommentWrite 컴포넌트를 두 곳에서 사용하고 있습니다 1번에서는 아무런 props 인자를 넘겨주지 않고 있고요 2번에서는 3가지 props 인자를 넘겨주고 있습니다 types 파일 export interface ICommentWrite { item?: IBoardComment; isEdit?: boolean; setIsEdit?: Dispatch<SetStateAction<boolean>>; } 이에 맞춰 작성한 interface 입니다 setIsEdit state에 ? 기호를 붙이니 CommentWrite 파일(바로 아래 파일)의 props.setIsEdit state 사용 구간에서 '정의되지 않음'일 수 있는 개체를 호출할 수 없다는 오류가 뜹니다 export default function CommentWrite(props: ICommentWrite): JSX.Element { const onClickUpdate = async (): Promise<void> => { . . . props.setIsEdit(false); }; const onClickCancel = (): void => { props.setIsEdit(false); }; return ( . . . ); } 찾아보니 undefined / null 값을 제대로 다루지 못할 때 생기는 오류라고 하는데요 해당 state는 한 곳에서만 props 인자로 전달하고 있기 때문에 undefined 값이 나오는 경우가 필연적입니다 이런 경우 해결할 수 있는 방법이 있을까요? 만약 타입 지정과 관련된 방법으로 해결할 수 없는 문제라면 props 인자를 한 곳에서만 받도록 파일을 합칠까 합니다

  • react
  • node.js
  • graphql
  • next.js
zero.1.0.one.xx 댓글 1 좋아요 0 조회수 981

인기 태그

인프런 TOP Writers

주간 인기글