Tech/React

[React] 고객 정보 삭제 기능 구현하기

lonnie(동현) 2021. 3. 18. 16:30

➖ 고객 정보 삭제 기능 구현하기

DB 테이블에서 완전히 제거하지 않고 DB 테이블 상에서 데이터가 삭제되었다고 체크만 하고 실제로 DB에서 해당 데이터를 완전히 삭제하지 않는 방법으로 개발을 진행해보겠다. 왜냐하면 데이터가 언제 삭제가 되었는지 등에 대한 정보를 기록할 수 있기 때문이다.

0️⃣ 고객 정보가 담긴 CUSTOMER 테이블 수정하기

1) 고객 데이터가 삭제가 되었는지에 대한 데이터를 담을 컬럼 추가

USE management;

ALTER TABLE CUSTOMER ADD createDate DATETIME;
ALTER TABLE CUSTOMER ADD isDeleted INT;

2) 생성된 컬럼을 NULL로 비워두면 좋지 않기 때문에 데이터를 채워준다.

USE management;

UPDATE CUSTOMER SET createDate = NOW();
UPDATE CUSTOMER SET isDeleted = 0;

1️⃣ CustomerDelete 컴포넌트 만들기(./client/src/components/CustomerDelte.js)

1) deleteCustomer라는 API 함수를 만들어 준다. 고객의 id가 매개 변수로 들어왔을 때 삭제를 진행할 수 있도록 해준다. REST API에서는 해당 URL에 접근해서 삭제를 진행할 수 있다.

import React from 'react';

class CustomerDelete extends React.Component {

    deleteCustomer(id){
        const url = '/api/customers/' + id;
    }

    render(){
        return(
            <button > 삭제 </button> 
        )
    }
}

2) DELETE 메서드를 통해 해당 URL에 접속할 수 있는 코드를 작성한다.

import React from 'react';

class CustomerDelete extends React.Component {

    deleteCustomer(id){
        const url = '/api/customers/' + id;
                fetch(url, {
                        method : 'DELETE'
                });
    }
    render(){
        return(
            <button > 삭제 </button> 
        )
    }
}

3) 삭제 이후에 새롭게 바뀐 고객 목록을 다시 화면에 출력할 수 있도록 한다.

import React from 'react';

class CustomerDelete extends React.Component {

    deleteCustomer(id){
        const url = '/api/customers/' + id;
                fetch(url, {
                        method : 'DELETE'
                });
                this.props.stateRefresh();
    }
    render(){
        return(
            <button > 삭제 </button> 
        )
    }
}

4) 실제로 삭제 버튼을 눌렀을 때 삭제가 이루어질 수 있도록 한다.

import React from 'react';

class CustomerDelete extends React.Component {

    deleteCustomer(id){
        const url = '/api/customers/' + id;
        fetch(url,{
            method : 'DELETE'

        })
        this.props.stateRefresh();
    }
    render(){
        return(
            <button onclick = {(e) => {this.deleteCustomer(this.props.id)}} > 삭제 </button> 
        )
    }
}

export default CustomerDelete;

2️⃣ 삭제 버튼 추가하기(./client/src/components/Customer.js)

1) 어떤 id값이 삭제 되는지, 삭제 후 새로 고침을 할 수 있도록 하고 삭제 버튼을 한 행의 마지막에 보일 수 있도록 한다.

<TableCell>
    <CutomerDelete 
            stateRefresh={this.props.stateRefresh}
            id={this.props.id}/>
</TableCell>

3️⃣ App.js에 반영하기(./client/src/components/App.js)

1) TableCell을 추가하고 부모에서 자식으로 함수 데이터가 넘어갈 수 있도록 한다.

<TableCell>설정</TableCell>
this.state.customers ? this.state.customers.map(c => {
     return(
       <Customer stateRefresh={this.stateRefresh}
           key      = {c.id} 
           id       = {c.id}
           image    = {c.image}
           name     = {c.name}
           birthday = {c.birthday}
           gender   = {c.gender}
           job      = {c.job}
        />
      );            
 })

4️⃣ server에서 DELETE 처리해주기(sever.js)

1) 삭제가 된 데이터는 1로 처리해준다.

app.delete('/api/customers/:id', (req, res) => {
    let sql = 'UPDATE CUSTOMER SET isDeleted = 1 WHERE id = ?';
    let params = [req.param.id];
    connection.query(sql, params,
        (err, rows, fields) => {
            res.send(rows);
        }
    )
})

2) 삭제된 데이터를 제외하고 가져와야 하기 때문에 0인 데이터만 가져올 수 있도록 한다.

app.get('/api/customers', (req, res) => {
    connection.query(
        "SELECT * FROM CUSTOMER WHERE isDeleted =0",
        (err, rows, fields) => {
            res.send(rows);
        }
    )
});

3) 고객 추가시에도 초기 데이터 값에서 삭제가 되지 않았다는 것을 표현해주기 위해 0을 표시해준다.

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);
        }
    );
})

5️⃣ 마무리

이로써 고객의 정보를 삭제하는 기능까지 구현을 완료하였다.

728x90
반응형