2018~2019/React.js

4. React와 Express, MongoDB 연동하기 (3) DELETE

전기도둑 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' 데이터를 삭제된 것을 확인 할 수 있음.