묻고 답해요
158만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
db관련 질문있습니다.
postgres 주소는 오프라인 강의 시에만 제공하고 온라인은 제공을 하지 않는다고 이해했는데요.해당 부분으로 대체 가능한 방법과 postgres 없이 graphql만 실행하여 강의를 따라가도 지장이 없는지 궁금합니다.이후 강의에는 데이터 처리하는 부분이 포함되어있는 것 같은데요. 해당부분 확인 바랍니다!
-
미해결한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
npm init 을 터미널에 입력하면 사진과 같은 오류가 납니다.
3.3)Node.js 사용하기강의 3분10초입니다.npm init 을 터미널에 입력하면 사진과 같은 오류가 납니다.
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
AxiosError {message: 'Request failed with status code 401/500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE',
로그인 페이지에서 로그인을 하면 500, 커뮤니티 생성 페이지에서 생성을 하면 401 AxiosError가 뜹니다. <login.tsx>import axios from 'axios'; import InputGroup from '../components/InputGroup' import Link from 'next/link' import { useRouter } from 'next/router'; import React,{ FormEvent, useState } from 'react' import { useAuthDispatch } from '../context/auth'; axios.defaults.withCredentials = true; const Login = () => { let router = useRouter(); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [errors, setErrors] = useState<any>({}); const dispatch = useAuthDispatch(); const handleSubmit = async (event: FormEvent) => { event.preventDefault(); try{ const res = await axios.post("/auth/login", {password, username}, {headers: {'Access-Control-Allow-Origin': 'http://localhost:3000'}}) dispatch("LOGIN", res.data?.user); } catch(error: any){ //console.log(error); setErrors(error.response?.data || {}) } } return ( <div className='bg-white'> <div className='flex flex-col items-center justify-center h-screen p-6'> <div className='w-10/12 mx-auto md:w-96'> <h1 className='mb-2 text-lg font-medium'>로그인</h1> <form onSubmit={handleSubmit}> <InputGroup placeholder='Username' value={username} setValue={setUsername} error={errors.username} /> <InputGroup placeholder='Password' value={password} setValue={setPassword} error={errors.password} /> <button className='w-full py-2 mb-1 text-xs font-bold text-white uppercase bg-gray-400 border border-gray-400 rounded'> 로그인 </button> </form> <small> 아직 아이디가 없으신가요? <Link href="/register" legacyBehavior> <a className='ml-1 text-blue-500 uppercase'>회원가입</a> </Link> </small> </div> </div> </div> ) } export default Login<create.tsx>import axios from "axios"; import { GetServerSideProps } from "next"; import InputGroup from "../../components/InputGroup" import {useState, FormEvent} from "react"; import {useRouter} from "next/router" axios.defaults.withCredentials = true; const SubCreate = () => { const [name, setName] = useState(""); const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [errors, setErrors] = useState<any>({}); let router = useRouter(); const handleSubmit = async (event: FormEvent) => { event.preventDefault(); try { const res = await axios.post("/subs", {name, title, description}, {headers: {'Access-Control-Allow-Origin': 'http://localhost:3000'}}) router.push(`/r/${res.data.name}`); } catch (error: any) { // console.log(error); setErrors(error.response?.data || {}); } } return ( <div className="flex flex-col justify-center pt-16"> <div className="w-10/12 mx-auto md:w-96"> <h1 className="mb-2 text-lg font-medium"> 그룹 만들기 </h1> <hr /> <form onSubmit={handleSubmit}> <div className="my-6"> <p className="font-medium">Name</p> <p className="mb-2 text-xs text-gray-400"> 그룹 이름은 변경할 수 없습니다. </p> <InputGroup placeholder="이름" value={name} setValue={setName} error={errors.name} /> </div> <div className="my-6"> <p className="font-medium">Title</p> <p className="mb-2 text-xs text-gray-400"> 주제를 입력해 주세요. </p> <InputGroup placeholder="주제" value={title} setValue={setTitle} error={errors.title} /> </div> <div className="my-6"> <p className="font-medium">Description</p> <p className="mb-2 text-xs text-gray-400"> 그룹에 대한 설명을 입력해주세요. </p> <InputGroup placeholder="설명" value={description} setValue={setDescription} error={errors.description} /> </div> <div className="flex jstify-end"> <button className="px-4 py-1 text-sm font-semibold rounded text-white bg-gray-400 border" > 그룹 만들기 </button> </div> </form> </div> </div> ) } export default SubCreate<subs.ts>import {Router, Request, Response} from "express"; import jwt from "jsonwebtoken" import { User } from "../entities/User"; import userMiddleware from "../middlewares/user" import authMiddleware from "../middlewares/auth" import { AppDataSource } from "../data-source"; import Sub from "../entities/Sub"; import { isEmpty } from "class-validator"; const createSub = async (req: Request, res: Response, next) => { const {name, title, description} = req.body; try { let errors: any = {}; if (isEmpty(name)) errors.name = "이름은 비워둘 수 없습니다."; if (isEmpty(title)) errors.title = "제목은 비워둘 수 없습니다."; const sub = await AppDataSource.getRepository(Sub) .createQueryBuilder("sub") .where("lower(sub.name) = :name", { name: name.toLowerCase() }) .getOne(); if (sub) errors.name = "서브가 이미 존재합니다."; if (Object.keys(errors).length > 0) { throw errors; } } catch (error) { console.log(error); return res.status(500).json({ error: "문제가 발생했습니다." }); } try { const user: User = res.locals.user; const sub = new Sub(); sub.name = name; sub.description = description; sub.title = title; sub.user = user; await sub.save(); return res.json(sub); } catch (error) { console.log(error); return res.status(500).json({ error: "문제가 발생했습니다." }); } }; const router = Router(); router.post("/", userMiddleware,authMiddleware, createSub); export default router; <server.ts>import express, { response } from "express"; import morgan from "morgan"; import { AppDataSource } from "./data-source"; import authRoutes from './routes/auth' import subRoutes from './routes/subs' import cors from 'cors'; import dotenv from 'dotenv'; import cookieParser from "cookie-parser"; const app = express(); const origin = process.env.ORIGIN; const corsOption = { origin: "http://localhost:3000", credentials: true } app.use(cors(corsOption)) app.use(express.json()); app.use(morgan('dev')); app.use(cookieParser()); dotenv.config(); app.get("/", (_, res) => {res.send("running")}); app.use("/api/auth", authRoutes) app.use("/api/subs", subRoutes) console.log(process.env.ORIGIN) let port = 4000; app.listen(port, async () => { console.log('server running at http://localhost:${port}'); AppDataSource.initialize().then(async () =>{ console.log("database initialized") }).catch(error => console.log(error)) })
-
해결됨한 입 크기로 잘라먹는 Next.js(v15)
Image의 src에 경로를 작성하는 것과 import로 이미지를 가져와서 넣는 것의 차이가 궁금합니다!
<Image src="/logo.png" alt="로고" width={100} height={100} /> import Logo from "@/public/logo.png"; <Image src={Logo} alt="로고" width={100} height={100} />이 두가지 접근 방식의 차이가 있을까요?
-
미해결React 완벽 마스터: 기초 개념부터 린캔버스 프로젝트까지
조건부 렌더링중 &&와 버튼 3항 연산자가 화면처럼 안나오네요ㅠㅠ
CoursItem.jsxApp.jsx제 개발화면확인 부탁드립니다:)
-
해결됨한 입 크기로 잘라먹는 Next.js(v15)
포괄적 에러 핸들링 error.tsx이 정상 작동 하지 않습니다 (05:30)
안녕하세요서버는 종료한 상태에서 강의대로 (with-searchbar)/error.tsx 파일을 만들고 새로고침을 하면 error.tsx에서 작성한 페이지가 나오지 않습니다.error.tsx 인덱스 페이지 아래 사진처럼 error.tsx페이지가 아닌핸들링되지 않은 런타임 에러가 발생해버립니다..혹시 searchParams를 Promise객체로 타입정의 한것처럼 뭔가 사용방법이 바뀐걸까요..?
-
해결됨한 입 크기로 잘라먹는 Next.js(v15)
skeleton UI 적용 시점
안녕하세요 현재 6.4)스켈레톤 UI 적용하기 강의를 듣고나서 궁금한점이 있어 질문 남깁니다. 서버쪽 데이터요청이 오래 걸리는 경우 Suspense를 통해 Skeleton UI를 보여주고 이후 데이터가 적용 된 컴포넌트를 보여주는거로 알고 있습니다.그래서 사용자경험이 조금 오를 것 같긴한데, 만약 데이터 요청이 빠른 경우(0.5초만에 데이터처리가 이뤄진 경우)에는 오히려 UX 관점에서 불편하지 않을까 싶어서 이럴땐 어떻게 처리하는게 좋을 지 질문 남깁니다!예시) 책 검색 -> 책 리스트의 skeleton UI 가 잠깐 보였다가(0.5초 등장) -> 책 리스트 나타남 (이와 같은 과정이 이뤄지면 오히려 사용자 경험이 떨어지지 않을까 싶어 궁금합니다)
-
해결됨한 입 크기로 잘라먹는 Next.js(v15)
2-16 ssg 구현중 에러입니다.
안녕하세요 강사님, 강의를 듣는 중 문제가 발생해 글 남깁니다.book/id 상세페이지에서 SSG getStaticPaths를 적용중인데, id를 인식을 못해 에러가 발생합니다.Error: A required parameter (id) was not provided as an array received string in getStaticPaths for /book/[[...id]]강의에 의하면, books/1 은 보여야 하는데 페이지가 보이지 않네요오타인 것 같아 강사님 깃헙 코드도 복사해서 붙여봤는데 에러가 납니다 혹시 다른 문제가 있을까요? 에러 메세지에는 id가 제공이 안된다고 하는데, 제가 보기에는 staticProps에 맞게 변경한거 같은데, 왜 에러가 날까요??
-
해결됨React 완벽 마스터: 기초 개념부터 린캔버스 프로젝트까지
노드(express) 연동
유튜브에 올라온 js강의가 너무 만족스러워서 강의를 신청하였고,현재 강의 잘듣고 있습니다. 저는 노드 공부를 하였고, 프론트 부분을 리액트로 하고 싶어서 강의를 듣고 있는데혹시 노드(express)와 연동 해서 프로젝트를 하고 싶은데 괜찮은 자료나강의가 있을까요?
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 챗봇 사이트 만들기
localhost:3000 ERR_CONNECTION_REFUSED
npm run dev로 서버는 성공적으로 올라갔는데 localhost:3000 접속 시 연결이 거부되었다고 뜹니다.이것저것 많이 찾아보긴 했는데 해결이 안되네요 ㅠㅠwindows, 크롬에서 실행했습니다. 해결 방법을 알 수 있을까요?// index.js const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const app = express(); const config = require("./server/config/keys"); // const mongoose = require("mongoose"); // mongoose.connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) // .then(() => console.log('MongoDB Connected...')) // .catch(err => console.log(err)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api/dialogflow', require('./server/routes/dialogflow')); // Serve static assets if in production if (process.env.NODE_ENV === "production") { // Set static folder app.use(express.static("client/build")); // index.html for all page routes app.get("*", (req, res) => { res.sendFile(path.resolve(__dirname, "client", "build", "index.html")); }); } const port = process.env.PORT || 5000; app.listen(port, () => { console.log(`Server Running at ${port}`) }); //package.json { "name": "chatbot-app", "version": "1.0.0", "description": "chatbot-app", "main": "index.js", "engines": { "node": "18.20.5", "npm": "10.9.0" }, "scripts": { "start": "node index.js", "backend": "nodemon index.js", "frontend": "npm run front --prefix client", "dev": "concurrently \"npm run backend\" \"npm run start --prefix client\"" }, "author": "Jaewon Ahn", "license": "ISC", "dependencies": { "actions-on-google": "^3.0.0", "body-parser": "^1.20.3", "dialogflow": "^1.2.0", "dialogflow-fulfillment": "^0.6.1", "dotenv": "^16.4.5", "express": "^4.21.1", "mongoose": "^8.8.1", "node": "^18.20.5", "punycode": "^2.3.1" }, "devDependencies": { "@ant-design/icons": "^5.5.1", "@babel/plugin-proposal-private-property-in-object": "^7.21.11", "concurrently": "^9.1.0", "nodemon": "^3.1.7" } } client쪽//package.json { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "antd": "^4.24.16", "axios": "^1.7.7", "prop-types": "^15.8.1", "react": "^18.3.1", "react-dom": "^18.3.1", "react-redux": "^9.1.2", "react-router-dom": "^6.28.0", "react-scripts": "5.0.1", "redux": "^5.0.1", "redux-promise": "^0.6.0", "redux-thunk": "^3.1.0", "uuid": "^11.0.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "http-proxy-middleware": "^3.0.3" } }
-
해결됨한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
Home이 화면에 안 떠요
import "./App.css"; import { Routes, Route } from "react-router-dom"; import Home from "./pages/Home"; import Diary from "./pages/Diary"; import New from "./pages/New"; // 1. "/" : 모든 일기를 조회하는 Home 페이지 // 2. "/new" : 새로운 일기를 작성하는 New 페이지 // 3. "/diary" : 일기를 상세히 조회하는 Diary 페이지 function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/new" element={<New />} /> <Route path="/diary" element={<Diary />} /> </Routes> ); } export default App; const Home = () => { return <div>Home</div>; }; export default Home;이렇게 작성했고, 오타도 없는 것 같은데 화면에 home이라는 글자가 안 뜹니다. router도 6.28. 으로 설치됐습니다.
-
미해결파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)
cover_image_tag(self) 부분 질문이 있습니다.
안녕하세요 강사님.인자로 받는 self는 그 c++의 this 포인터 같은 개념으로 보면 될까요, 그리고 list_display 안에 cover_image를 cover_image_tag로 바꿨는데 처음에 cover_image는 같은 클래스(SongAdmin)에 있는 함수라 list_display에서 사용가능한거고, cover_image_tag는 models 파일 안에 Song 클래스 안에 있는 함수라 list_display에서 사용이 가능한걸까요? 감사합니다.
-
해결됨파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)
[11-30] 강의 crispy form 적용에서 오류가 발생해서 관련 문의 드립니다.
강사님 안녕하세요,HTMX와 모달을 활용한 댓글 기능을 구현하는 코드 작성 중에 crispy form이 적용이 되지 않고 오류가 발생해서 문의드립니다.작성하고 있던 코드는 _comment_form.html 파일의 코드입니다아래 이미지는 발생한 에러 내용입니다. comment_form.html 파일의 코드를 구현하고 로컬호스트에 띄운 개별 Note 페이지의 하단에 '댓글 쓰기' 버튼을 클릭했을 때, crispy form이 렌더링 되지 않고 위와 같은 에러가 발생하는 케이스입니다. 제가 추측하는 것은 context 변수에 담긴 데이터에 문제가 있어서, flatten() 메서드가 동작하지 않아 발생하는 에러 같다고 생각하는데요. 해결하는 방법에 대해 알려주시면 감사하겠습니다! 감사합니다 🙂
-
미해결Slack 클론 코딩[실시간 채팅 with React]
CORS - Access-Control-Allow-Origin 누락 문제
강좌보면서 proxy 설정하고 back 폴더 npm run dev, alecture 폴더 npm run build 했는데 회원가입 버튼을 누르니 콘솔창에 시간차로 계속 Access to XMLHttpRequest at 'https://sleact.nodebird.com/api/users' from origin 'http://localhost:3095' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.app.js:2 GET https://sleact.nodebird.com/api/users net::ERR_FAILED 200 (OK)(익명) @ app.js:2e.exports @ app.js:2e.exports @ app.js:2l.request @ app.js:2r.forEach.l.<computed> @ app.js:2(익명) @ app.js:2r.Z @ 678.js:1(익명) @ app.js:2(익명) @ app.js:2(익명) @ app.js:2(익명) @ app.js:2o @ app.js:2(익명) @ app.js:2(익명) @ app.js:2D @ app.js:2[신규] Edge에서 Copilot을 사용하여 콘솔 오류 설명: 클릭 오류를 설명합니다. 자세한 정보 다시 표시 안 함signup:1 Access to XMLHttpRequest at 'https://sleact.nodebird.com/api/users' from origin 'http://localhost:3095' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.app.js:2 GET https://sleact.nodebird.com/api/users net::ERR_FAILED 200 (OK)(익명) @ app.js:2e.exports @ app.js:2e.exports @ app.js:2l.request @ app.js:2r.forEach.l.<computed> @ app.js:2(익명) @ app.js:2r.Z @ 678.js:1(익명) @ app.js:2(익명) @ app.js:2(익명) @ app.js:2(익명) @ app.js:2o @ app.js:2(익명) @ app.js:2setTimeoutonErrorRetry @ app.js:2(익명) @ app.js:2(익명) @ app.js:2(익명) @ app.js:2u @ app.js:2Promise.thenc @ app.js:2(익명) @ app.js:2o @ app.js:2(익명) @ app.js:2(익명) @ app.js:2D @ app.js:2signup:1 Access to XMLHttpRequest at 'https://sleact.nodebird.com/api/users' from origin 'http://localhost:3095' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.319.js:1 undefinedapp.js:2 POST https://sleact.nodebird.com/api/users net::ERR_FAILED라는 오류가 발생합니다. copilot을 실행시켜보니 Access-Control-Allow-Origin과 Origin이 같아야하는데 Access-Control-Allow-Origin 부분이 누락되었다고 나옵니다. 네트워크 200번대는 실행에는 성공한거라고 들었는데... 도움주시면 감사하겠습니다!제 webpack.config.ts 첨부하겠습니다. import path from 'path'; //import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin'; import webpack, { Configuration as WebpackConfiguration } from "webpack"; import { Configuration as WebpackDevServerConfiguration } from "webpack-dev-server"; //import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'; interface Configuration extends WebpackConfiguration { devServer?: WebpackDevServerConfiguration; } import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; const isDevelopment = process.env.NODE_ENV !== 'production'; const config: Configuration = { name: 'sleact', mode: isDevelopment ? 'development' : 'production', devtool: !isDevelopment ? 'hidden-source-map' : 'eval', resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'], alias: { '@hooks': path.resolve(__dirname, 'hooks'), '@components': path.resolve(__dirname, 'components'), '@layouts': path.resolve(__dirname, 'layouts'), '@pages': path.resolve(__dirname, 'pages'), '@utils': path.resolve(__dirname, 'utils'), '@typings': path.resolve(__dirname, 'typings'), }, }, entry: { app: './client', }, module: { rules: [ { test: /\.tsx?$/, loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { targets: { browsers: ['IE 10'] }, debug: isDevelopment, }, ], '@babel/preset-react', '@babel/preset-typescript', ], env: { development: { plugins: [require.resolve('react-refresh/babel')], }, }, }, exclude: path.join(__dirname, 'node_modules'), }, { test: /\.css?$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ // new ForkTsCheckerWebpackPlugin({ // async: false, // // eslint: { // // files: "./src/**/*", // // }, // }), new webpack.EnvironmentPlugin({ NODE_ENV: isDevelopment ? 'development' : 'production' }), ], output: { path: path.join(__dirname, 'dist'), filename: '[name].js', publicPath: '/dist/', }, devServer: { historyApiFallback: true, // react router port: 3090, devMiddleware: { publicPath: '/dist/' }, static: { directory: path.resolve(__dirname) }, proxy: { '/api/': { target: 'http://localhost:3095', changeOrigin: true, }, }, }, }; if (isDevelopment && config.plugins) { // config.plugins.push(new webpack.HotModuleReplacementPlugin()); // // config.plugins.push(new ReactRefreshWebpackPlugin()); // // config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'server', openAnalyzer: true })); } if (!isDevelopment && config.plugins) { // config.plugins.push(new webpack.LoaderOptionsPlugin({ minimize: true })); // // config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'static' })); } export default config;
-
해결됨한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
12.11 invalid Date 오류
따라서 하고 있었는데 다음 그림과 같이 invalid Date 라는 값이 떠서 관련 질문 드립니다. 강의 몇번 돌려보면서 오타가 있나 봤는데 도저히 모르겠어서 질문 드립니다...// App.jsx import "./App.css"; import { Routes, Route, Link, useNavigate } from "react-router-dom"; import Home from "./pages/Home"; import Diary from "./pages/Diary"; import New from "./pages/New"; import Edit from "./pages/Edit"; import Notfound from "./pages/Notfound"; import { useReducer, useRef, createContext } from "react"; const mockData = [ { id: 1, createdDate: new Date("2024-11-13").getTime(), emotionId: 1, content: "1번 일기 내용", }, { id: 2, createdDate: new Date("2024-11-10").getTime(), emotionId: 2, content: "2번 일기 내용", }, { id: 3, createdDate: new Date("2024-10-11").getTime(), emotionId: 3, content: "3번 일기 내용", }, ]; function reducer(state, action) { switch (action.type) { case "CREATE": return [action.data, ...state]; case "UPDATE": return state.map((item) => String(item.id) === String(action.data.id) ? action.date : item ); case "DELETE": return state.filter((item) => String(item.id) !== String(action.id)); default: return state; } } export const DiaryStateContext = createContext(); export const DiaryDispatchContext = createContext(); function App() { const [data, dispatch] = useReducer(reducer, mockData); const idRef = useRef(3); const onCreate = (createdDate, emotionId, content) => { dispatch({ type: "CREATE", data: { id: idRef.current++, createdDate, emotionId, content, }, }); }; const onUpdate = (id, createdDate, emotionId, content) => { dispatch({ type: "UPDATE", data: { id, createdDate, emotionId, content, }, }); }; const onDelete = (id) => { dispatch({ type: "DELETE", id, }); }; return ( <> <DiaryStateContext.Provider value={data}> <DiaryDispatchContext.Provider value={{ onCreate, onDelete, onUpdate }}> <Routes> <Route path="/" element={<Home />} /> <Route path="/new" element={<New />} /> <Route path="/diary/:id" element={<Diary />} /> <Route path="/edit/:id" element={<Edit />} /> <Route path="*" element={<Notfound />} /> </Routes> </DiaryDispatchContext.Provider> </DiaryStateContext.Provider> </> ); } export default App; //Home.jsx import { useState, useContext } from "react"; import { DiaryStateContext } from "../App"; import DiaryList from "../components/DiaryList"; import Header from "../components/Header"; import Button from "../components/button"; const getMonthlyData = (pivotDate, data) => { const beginTime = new Date( pivotDate.getFullYear(), pivotDate.getMonth(), 1, 0, 0, 0 ).getTime(); const endTime = new Date( pivotDate.getFullYear(), pivotDate.getMonth() + 1, 0, 23, 59, 59 ).getTime(); return data.filter( (item) => beginTime <= item.createdDate && item.createdDate <= endTime ); }; const Home = () => { const data = useContext(DiaryStateContext); const [pivotDate, setPivotDate] = useState(new Date()); const monthlyData = getMonthlyData(pivotDate, data); console.log(monthlyData); const onIncreaseMonth = () => { setPivotDate(new Date(pivotDate.getFullYear(), pivotDate.getMonth() + 1)); }; const onDecreaseMonth = () => { setPivotDate(new Date(pivotDate.getFullYear(), pivotDate.getMonth() - 1)); }; return ( <div> <Header title={`${pivotDate.getFullYear()}년 ${pivotDate.getMonth() + 1}월`} leftChild={<Button onClick={onDecreaseMonth} text={"<"} />} rightChild={<Button onClick={onIncreaseMonth} text={">"} />} /> <DiaryList data={monthlyData} /> </div> ); }; export default Home; //diaryList.jsx import Button from "./button"; import "./DiaryList.css"; import DiaryItem from "./DiaryItem"; const DiaryList = ({ data }) => { return ( <div className="DiaryList"> <div className="menu_bar"> <select> <option value={"latest"}>최신순</option> <option value={"oldest"}>오래된 순</option> </select> <Button text={"새 일기 쓰기"} type={"POSITIVE"} /> </div> <div className="list_wrapper"> {data.map((item) => ( <DiaryItem key={item.id} {...item} /> ))} </div> </div> ); }; export default DiaryList; //DiaryItem.jsx import { getEmotionImage } from "../util/get-emotion-image"; import Button from "./button"; import "./DiaryItem.css"; const DiaryItem = (id, emotionId, createdDate, content) => { return ( <div className="DiaryItem"> <div className={`img_section img_section_${emotionId}`}> <img src={getEmotionImage(1)} /> </div> <div className="info_seciton"> <div className="created_date"> {new Date(createdDate).toLocaleDateString()} </div> <div className="content">{content}</div> </div> <div className="button_section"> <Button text={"수정하기"} /> </div> </div> ); }; export default DiaryItem;
-
미해결(2025 최신 업데이트)리액트 : 프론트엔드 개발자로 가는 마지막 단계
전체 소스코드는 어디서 받을 수 있나요?
전체 소스코드는 어디서 받을 수 있나요?
-
해결됨따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
overload 에러
import {Router, Request, Response} from "express"; import {User} from "../entities/User"; import { validate, Validate } from "class-validator"; const register = async (req: Request, res: Response) => { const {email, username, password} = req.body; try{ let errors: any = {}; //이메일/유저이름 단일성 확인 const emailUser = await User.findOneBy({email}); const usernameUser = await User.findOneBy({username}); //이미 있으면 erros 객체에 넣음 if(emailUser) errors.email = "이미 해당 이메일 주소가 사용되었습니다." if(usernameUser) errors.username = "이미 사용자 이름이 사용되었습니다." //에러가 있으면 return으로 에러를 response 보내줌 if(Object.keys(errors).length > 0){ return res.status(400).json(errors) } const user = new User(); user.email = email; user.username = username; user.password = password; //엔터티에 정해 놓은 조건으로 user 데이터 유호성 검사를 해줌 errors = await validate(user); //유저 정보를 user table에 저장 await user.save() return res.json(user); } catch(error){ console.error(error); return res.status(500).json({error}) } } const router = Router(); router.post("/register", register); export default router맨 위 코드(auth.ts)에서 사진과 같이 overload 에러가 뜹니다.유저이름/이메일 중복 및 에러 처리하는 코드 중 return으로 응답을 반환하는 중 타입이 맞지 않아서 생기는 오류 같은데 어떻게 해결할 수 있을까요??
-
미해결이미지 관리 풀스택(feat. Node.js, React, MongoDB, AWS)
소스코드 요청
혹시 강의 소스코드 받아 올 수 있을까요?제가 백엔드는 다 작성 했는데 프론트 쪽 하시는 분이 외국 분이라 설명하기에는 어렵고 해서 요청드립니다.
-
해결됨한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
vercel 배포
배포는 잘 된 것 같은데요...? 계속 데이터 로딩중 페이지만 떠서 여쭤봅니다. 제 생각에는 받아올 데이터가 없어서 빈배열이라서 문제가 되는걸까 싶었지만, 선생님 강의에서도 동일하게 빈배열이지만 Header가 잘 나오는거보면 랜더링이 정상적으로 되는 것 같아서 받아올 데이터가 없는건 문제가 아닌듯하여 질문하게되었습니다. 혹시나 권한 오류일까 싶어 질문답변 글 참고하여 적용해봤으나 아닌 것 같습니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
검색 결과 페이지네이션 1페이지(일단해결)
결론부터 말하면 검색할 때 페이지네이션 현재 페이지가 1로 안 바뀌어서 바꿔봤습니다.예를 들어 ‘철’이라는 검색어를 입력했더니 페이지가 2페이지까지 있음. 2페이지를 클릭해 2페이지가 보이는 상태에서 검색어를 ‘철수’로 바꾸니 게시글 수가 1페이지까지밖에 없었는데, 1페이지가 현재 activedPage가 아니게 됨(없어진 2페이지 그대로).검색한 게시글 목록 refetch는 제대로 이루어지기에 1페이지의 내용이 보이는 것은 맞지만 현재 페이지 숫자가 제대로 표시되지 않음. 또한 ‘안녕하세요’의 12페이지를 보고 있었는데 ‘안녕’으로 검색어를 바꾸니 당연히 refetch를 통해 1페이지 게시글 목록을 보여주지만, 페이지네이션은 그대로 11, 12, ..., 20임검색어가 바뀌면 페이지네이션의 activedPage와 startPage를 1로 변경해주도록 Paginations01.container에서 useEffect 실행시켜 해결 useEffect(() => { setStartPage(1); setActivedPage(1); }, [props.count]);검색어를 바꾸면 검색된 총 게시글 수도 보통 달라질 거라는 생각에 props.count를 의존성으로 써본건데 검색어를 바꿔도 우연히 검색된 총 게시글 수가 똑같을 경우 useEffect 실행 안 되니정말로 검색어가 달라질 때를 기준으로 하려고BoardList에 있는 keyword를 pagination 컴포넌트에 props로 넘겨줘서 사용// BoardList.presenter.tsx <Paginations01 refetch={props.refetch} count={props.count} keyword={props.keyword} /> // keyword 전달 // Paginations01.container.tsx useEffect(() => { setStartPage(1); setActivedPage(1); }, [props.keyword]); // Paginations01.types.ts export interface IPaginations01Props { ... keyword?: string; ... } 고쳐지긴 했는데 일단 useEffect에서 setState를 하고 있다는 점(여기선 크게 상관이 없는건지?)과페이지네이션 컴포넌트인데 keyword라는 걸 받아온다는 것 자체가 검색 컴포넌트의 영향을 받는다는 뜻 아닌가 싶어서(keyword는 검색 기능이 있을 때만 존재하니까) 제대로 된 컴포넌트 분리에 대한 고민(keyword?로 하면 페이지네이션 컴포넌트 쓸 때 keyword 써도 되고 안 써도 되니까 이대로 해도 괜찮을지...?)다른 방법은 있는지?의견 있으시면 알려주시면 감사하겠습니다. 그외 궁금한 점저는 이거 하는 과정에서 yarn dev 해놓은 상태에서 코드들을 저장 계속 하면서 고쳤는데 그럼 원래 바로바로 반영이 되잖아요. 코드에는 문제가 없어서 제대로 작동해야 했는데 페이지네이션 컴포넌트에서 props.keyword가 자꾸 undefined인 바람에 useEffect도 작동 안해서코드가 문젠줄 알고 한참 삽질 후 그냥 vscode와 크롬 등등 다 끄고 좀 나중에 그대로 다시 켜보니까 잘 작동하게 됐는데 (yarn dev를 끊었다 다시 하는 거로는 아마 해결 안됐음)이게 처음이 아니고 저번에도 한 번 포기하고 결국 다음날 켜보니까 코드는 그대로인데 갑자기 잘 되었는데정확히 무엇때문에 이런 문제가 생기는건지 모르겠네요!!! (캐시? .next? 뭐 그런 거 때문인가요?)