-
5. React와 Express, MongoDB 연동하기 (4) UPDATE2018~2019/React.js 2018. 10. 6. 00:16
UPDATE
1. react-client/src/App.js 수정
import React, { Component } from 'react';import './App.css';class App extends Component {constructor(props) {super();this.state = {users: [],name : '',age : '',};}componentDidMount() {this.getUser();}getUser = () => {fetch('/users').then(res => res.json()).then(users => this.setState({ users }));}handleChange = (e) => {this.setState({[e.target.name]: e.target.value});}handleClick = () => {const { name, age } = this.state;fetch('/users', {method: 'POST',body: JSON.stringify({name,age,}),headers: {'Accept': 'application/json','Content-Type': 'application/json'},}).then(res => this.getUser());document.getElementById('name').value = "";document.getElementById('age').value = "";}handleupdate = (e) => {e.preventDefault();const { id } = e.target;const name = prompt("바꿀 이름을 입력하세요.");if(!name) {return alert("이름을 입력해주세요.");}fetch(`/users/${id}`, {method: 'PATCH',body: JSON.stringify({name,}),headers: {'Accept': 'application/json','Content-Type': 'application/json'}}).then(res => this.getUser());}handledelete = (e) => {e.preventDefault();const { id } = e.target;fetch(`/users/${id}`, {method: 'DELETE',headers: {'Accept': 'application/json','Content-Type': 'application/json'},}).then(res => this.getUser());}render() {return (<div className="App"><h1>Users</h1><p>이름 : <input id="name" name="name" onChange={this.handleChange}></input><br/>나이 : <input id="age" name="age" onChange={this.handleChange}></input><br /><button onClick={this.handleClick}>등록</button></p>{this.state.users.map(user =><div key={user._id}>{user.name} {user.age}<button id={user._id} onClick={this.handleupdate}>수정</button><button id={user._id} onClick={this.handledelete}>삭제</button></div>)}</div>);}}export default App;2. react-server/routes/user.js 수정
import express from 'express';import User from '../schemas/user';const router = express.Router();router.get('/', async (req, res, next) => {const users = await User.find({});res.json(users);});router.post('/', (req, res, next) => {const user = new User({name : req.body.name,age : req.body.age,});user.save().then((result) => {console.log(result);res.status(201).json(result);});});router.patch('/:id', async (req, res, next) => {await User.findOneAndUpdate({_id: req.params.id}, {name: req.body.name,}).then((result) => {console.log(result);res.json(result);});});router.delete('/:id', async (req, res, next) => {await User.findOneAndRemove({_id: req.params.id}).then((result) => {console.log(result);res.json(result);});});module.exports = router;# PUT 대신 PATCH를 사용한 이유
- PUT : 전체를 변경하는 경우 (모든 필드 값을 변경함), 일부분만 전달시 나머지 필드는 null or 초기화 처리됨
- PATCH : 일부분만 변경하는 경우 (일부 필드 값만 변경함)
3. 결과
- npm start => http://localhost:3000/
=> 'Park 25' 데이터를 'Lee 25'로 이름이 변경된 걸 확인 할 수 있음
'2018~2019 > React.js' 카테고리의 다른 글
Chat App with ReactJS, Socket.io #1 (0) 2018.10.07 6. React와 Express, MongoDB 연동하기 - Socket.io (0) 2018.10.06 4. React와 Express, MongoDB 연동하기 (3) DELETE (0) 2018.10.05 3. React와 Express, MongoDB 연동하기 (2) Create (0) 2018.10.04 now.sh 느릴 때 (0) 2018.10.02