import { useContext, useState, useEffect } from "react"; import { DiaryStateContext } from "../App"; import { useNavigate } from "react-router-dom"; const useDiary = (id) => { const data = useContext(DiaryStateContext); const [currentDiaryItem, setCurrentDiaryitem] = useState(); const nav = useNavigate(); useEffect(() => { const currentDiaryItem = data.find( (item) => String(item.id) === String(id) ); if (!currentDiaryItem) { window.alert("존재하지 않는 일기입니다."); nav("/", { replace: true }); } setCurrentDiaryitem(currentDiaryItem); }, [id, data]); //data는 왜쓰는지? return currentDiaryItem; }; export default useDiary; 강의 내용코드입니다. 현재의 일기를 가져오는 커스텀훅입니다. 여기서 문제는 "존재하지 않는 일기입니다"라는 경고창이 2번뜹니다. http://localhost:5173/diary/1234 처럼 아무숫자나 입력했을 때 그리고 http://localhost:5173/ 으로 이동한 후에 경고창이 한번 더 뜹니다. useEffect가 id가 변함에 따라 계속 실행되어서라는 이유로 알고 있습니다. 그러면 왜 선생님코드에서는 경고창이 2번 뜨지 않았을까용? 그리고 의존성 배열에 [id, data] 2가지를 담는 이유가 궁금합니다. 현재 prams.id가 바뀔 때만 작동하게 해도 되지 않을까요? 사용자가 data를 수정하면서 페이지의 파라미터가 바뀌는 상황이 동시에 일어나지 않을 거 같아서요
const Editor = ({ onSubmit, initData }) => { const nav = useNavigate(); const [input, setInput] = useState({ createdDate: new Date(), // 여기서 그냥 getTime하면 안되나요? emotionId: 8, content: "", }); useEffect(() => { if (initData) { setInput({ ...initData, createdDate: new Date(Number(initData.createdDate)), }); } input의 createdDate와 initData의 createdDate 비교 기준이 new Date() 과 new Date().getTime() 로 달라서 useEffect안에서 createdDate: new Date(Number(initData.createdDate)), 이렇게 한다는 건 이해가 갑니다. 다만 처음부터 input의 createdDate를 new Date().getTime()으로 만들면 되지 않을까요?
#!/usr/bin/env node /** * Module dependencies. */ var app = require('../app'); var debug = require('debug')('suzil:server'); var http = require('http'); const mongoose = require("mongoose"); const userConfig = require("../config/userConfig.json"); let db = mongoose.connection; db.on("error",console.error); db.once("open",()=>{ console.log("Connected to mongo Server"); }); mongoose.connect( `mongodb+srv://wiyuchan1021:${userConfig.PW}>@suzilo.i1je5.mongodb.net/suzilo?retryWrites=true&w=majority`, {useNewUrlParser: true, useUnifiedTopology: true} ) /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /**f * Create HTTP server. */ var server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); } 코드 실행하면 PS C:\Users\yuchan\suzil> npm start > suzil@0.0.0 start > nodemon ./bin/www [nodemon] 3.1.7 [nodemon] to restart at any time, enter rs [nodemon] watching path(s): . [nodemon] watching extensions: js,mjs,cjs,json [nodemon] starting node ./bin/www (node:13580) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version (Use node --trace-warnings ... to show where the warning was created) (node:13580) [MONGODB DRIVER] Warning: useUnifiedTopology is a deprecated option: useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version MongoServerError: bad auth : authentication failed at Connection.sendCommand (C:\Users\yuchan\node_modules\mongodb\lib\cmap\connection.js:289:27) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Connection.command (C:\Users\yuchan\node_modules\mongodb\lib\cmap\connection.js:312:26) at async continueScramConversation (C:\Users\yuchan\node_modules\mongodb\lib\cmap\auth\scram.js:131:15) at async executeScram (C:\Users\yuchan\node_modules\mongodb\lib\cmap\auth\scram.js:80:5) at async ScramSHA1.auth (C:\Users\yuchan\node_modules\mongodb\lib\cmap\auth\scram.js:39:16) at async performInitialHandshake (C:\Users\yuchan\node_modules\mongodb\lib\cmap\connect.js:104:13) at async connect (C:\Users\yuchan\node_modules\mongodb\lib\cmap\connect.js:24:9) { errorResponse: { ok: 0, errmsg: 'bad auth : authentication failed', code: 8000, codeName: 'AtlasError' }, ok: 0, code: 8000, codeName: 'AtlasError', connectionGeneration: 0, [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' } } node:internal/process/promises:391 triggerUncaughtException(err, true /* fromPromise */); ^ MongoServerError: bad auth : authentication failed at Connection.sendCommand (C:\Users\yuchan\node_modules\mongodb\lib\cmap\connection.js:289:27) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Connection.command (C:\Users\yuchan\node_modules\mongodb\lib\cmap\connection.js:312:26) at async continueScramConversation (C:\Users\yuchan\node_modules\mongodb\lib\cmap\auth\scram.js:131:15) at async executeScram (C:\Users\yuchan\node_modules\mongodb\lib\cmap\auth\scram.js:80:5) at async ScramSHA1.auth (C:\Users\yuchan\node_modules\mongodb\lib\cmap\auth\scram.js:39:16) at async performInitialHandshake (C:\Users\yuchan\node_modules\mongodb\lib\cmap\connect.js:104:13) at async connect (C:\Users\yuchan\node_modules\mongodb\lib\cmap\connect.js:24:9) { errorResponse: { ok: 0, errmsg: 'bad auth : authentication failed', code: 8000, codeName: 'AtlasError' }, ok: 0, code: 8000, codeName: 'AtlasError', connectionGeneration: 0, [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' } } Node.js v20.17.0 [nodemon] app crashed - waiting for file changes before starting... 이러한 오류가 터미널에 뜨는데 왜 그런걸까요?
사물인터넷 통신은 내 손에 (Arduino, MQTT, Nodejs, MongoDB, Android,VS Code)
Drivers를 선택해서 나온 url주소로도 MongoDB for VS Code를 선택해서 나온 url주소로도 접속이 실패합니다. Node.js 코드는 다음과 같이 작성했습니다. const mongoose = require("mongoose"); const MONGODB_URL = "mongodb+srv://root:1234@education.sidnf.mongodb.net/"; mongoose .connect(MONGODB_URL) .then(() => console.log("Connected to database!")) .catch(() => console.log("Connection failed...")) Connection failed... 라고 나옵니다. Network Access에서도 0.0.0.0으로도 해보고, 제 컴퓨터의 IP주소로도 해보았습니다. 전부 접속 실패가 뜹니다. 이유를 알 수 있을까요?!
강의 12.3 보다가 의문이 들어서 질문 남깁니다. 강의에서 설명하고 사용하셨던 방법과 공식문서에서 BrowserRouter를 사용하는 방법이 달라서 헷갈립니다. 두가지 방법이 같은 것인지, 다르다면 어떻게 다른지 알려주세요 function App () { return ( < BrowserRouter basename = " /app "> < Routes > < Route path = " / " /> </ Routes > </ BrowserRouter > ); } =>공식문서에서는 이렇게 Routes를 BrowserRouter로 감싸서 사용했는데 강의 에서는 그러지 않아서 궁금합니다.!
안녕하세요 강사님, 강의 잘 듣고 있어요!! 다름이 아니라, 강사님 화면에서는 return 뒤에 작성하시고 소괄호가 자동으로 생성되면서 작성한 내용을 감싸주던데, 어떻게 하는건가요? ESLint, Prettier등 설치는 했어요 ㅠ.ㅠ 🚨 아래의 가이드라인을 꼭 읽고 질문을 올려주시기 바랍니다 🚨 질문 하시기 전에 꼭 확인해주세요 - 질문 전 구글에 먼저 검색해보세요 (답변을 기다리는 시간을 아낄 수 있습니다) - 코드에 오타가 없는지 면밀히 체크해보세요 (Date와 Data를 많이 헷갈리십니다) - 이전에 올린 질문에 달린 답변들에 꼭 반응해주세요 (질문에 대한 답변만 받으시고 쌩 가시면 속상해요 😢) 질문 하실때 꼭 확인하세요 - 제목만 보고도 무슨 문제가 있는지 대충 알 수 있도록 자세한 제목을 정해주세요 (단순 단어 X) - 질문의 배경정보를 제공해주세요 (이 문제가 언제 어떻게 발생했고 어디까지 시도해보셨는지) - 문제를 재현하도록 코드샌드박스나 깃허브 링크로 전달해주세요 (프로젝트 코드에서 문제가 발생할 경우) - 답변이 달렸다면 꼭 확인하고 반응을 남겨주세요 - 강의의 몇 분 몇 초 관련 질문인지 알려주세요! - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.
"devDependencies": { "webpack": "^4.41.5", "webpack-cli": "^3.3.10" } 수업과 동일한 명령어를 실행하려면 강의 내용과 동일한 버전을 사용하시면 문제 없이 실행됩니다. 버전이 바뀜에 따라 --help 결과물과 명령어 옵션들이 다소 변경되네요. (webpack major version이 4여도 변경 여부가 있습니다) 수업 노트에 webpack@4.41.5 버전을 사용하도록 안내해주시면 어떨까요?