삭제를 구현하는 방법은 다양한데 2가지를 예로 들어보겠다.
1. 삭제 시 테이블에서 완전히 삭제한다.
2. 삭제 시 테이블에서 완전히 제거하지 않고, 삭제되었다고 체크만 한다. (이렇게 구현해보겠다.)
ALTER TABLE CUSTOMER ADD createdDate DATETIME;
ALTER TABLE CUSTOMER ADD isDeleted INT;
SELECT * FROM CUSTOMER;
SET SQL_SAFE_UPDATES = 0;
UPDATE CUSTOMER SET createdDate = NOW();
UPDATE CUSTOMER SET isDeleted = 0;
SET SQL_SAFE_UPDATES = 1;
SELECT * FROM CUSTOMER;
DESC CUSTOMER;
import React from "react";
function CustomerDelete(props) {
const deleteCustomer = (id) => {
const url = '/api/customers/' + id;
fetch(url, {
method: 'DELETE;'
})
.then(() => {
props.stateRefresh();
})
.catch(err => console.log(err));
};
return (
<button onClick={() => {deleteCustomer(props.id)}}>삭제</button>
)
}
export default CustomerDelete;
어떤 녀석을 삭제할지 결정할 id를 넘겨주고 stateRefresh()함수도 넘겨준다.
<TableRow>
<TableCell>{this.props.id}</TableCell>
<TableCell><img src={this.props.image} alt="profile"/></TableCell>
<TableCell>{this.props.name}</TableCell>
<TableCell>{this.props.birthday}</TableCell>
<TableCell>{this.props.gender}</TableCell>
<TableCell>{this.props.job}</TableCell>
<TableCell><CustomerDelete stateRefresh={this.stateRefresh} id={this.props.id}/></TableCell>
</TableRow>
<TableRow>
<TableCell>번호</TableCell>
<TableCell>이미지</TableCell>
<TableCell>이름</TableCell>
<TableCell>생년월일</TableCell>
<TableCell>성별</TableCell>
<TableCell>직업</TableCell>
<TableCell>설정</TableCell>
</TableRow>
<Customer
stateRefresh={stateRefresh}
key={c.id}
id={c.id}
image={c.image}
name={c.name}
birthday={c.birthday}
gender={c.gender}
job={c.job}
/>
참고로, stateRefresh는 함수형에서 넘어가기 때문에 그냥 this 없이 넘긴다.
삭제 버튼 누르면 DELETE 날아가는것을 네트워크 창에서 볼 수 있다.
이제 Node.js Express 서버에서 삭제하는 부분을 구현하면 된다.
아래 코드를 추가한다.
app.delete('/api/customers/:id', (req, res) => {
let sql = 'UPDATE CUSTOMER SET isDeleted = 1 WHERE id = ?';
let params = [req.params.id];
connection.query(sql, params,
(err, rows, fields) => {
res.send(rows);
})
})
또한, 삭제되지 않은 데이터만 가져오기 위해 다음으로 코드를 수정한다.
app.get('/api/customers', (req, res) => {
connection.query(
"SELECT * FROM CUSTOMER WHERE isDeleted = 0",
(err, rows, fields) => {
res.send(rows);
}
);
});
데이터 삽입 시에도 새로 추가한 칼럼에 대한 값을 추가한다.
app.post('/api/customers', upload.single('image'), (req, res) => {
let sql = 'INSERT INTO CUSTOMER VALUES (null, ?, ?, ?, ?, ?, NOW(), 0)';
let image = '/image/' + req.file.filename;
let name = req.body.name;
let birthday = req.body.birthday;
let gender = req.body.gender;
let job = req.body.job;
let params = [image, name, birthday, gender, job];
connection.query(sql, params,
(err, rows, fields) => {
res.send(rows);
});
})
props로 stateRefresh를 넘길 때 문제가 발생.
CustomerDelete로 제대로 안넘어가는 상황.
props로 받아와서 props로 불러서 안넘겨서 그런거임.
<TableCell><CustomerDelete stateRefresh={this.props.stateRefresh} id={this.props.id}/></TableCell>
App.js에서는 함수를 선언했으니 그냥 넘기지만 이후에 props로 받은 녀석들은 props로 불러서 다시 넘겨야한다.
이제는 삭제할 때 마다 갱신되는 것을 볼 수 있다.