-
4. React와 Express, MongoDB 연동하기 (3) DELETE2018~2019/React.js 2018. 10. 5. 16:58
DELETE
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 = "";}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.handledelete}>삭제</button></div>)}</div>);}}export default App;2. react-server/route/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.delete('/:id', async (req, res, next) => {await User.findOneAndRemove({_id: req.params.id}).then((result) => {console.log(result);res.json(result);});});module.exports = router;3. 결과
- npm start => http://localhost:3000/
=> 'Shin 26' 데이터를 삭제된 것을 확인 할 수 있음.
'2018~2019 > React.js' 카테고리의 다른 글
6. React와 Express, MongoDB 연동하기 - Socket.io (0) 2018.10.06 5. React와 Express, MongoDB 연동하기 (4) UPDATE (0) 2018.10.06 3. React와 Express, MongoDB 연동하기 (2) Create (0) 2018.10.04 now.sh 느릴 때 (0) 2018.10.02 2. React와 Express, MongoDB 연동하기 (1) Retrieve (0) 2018.10.02