이번에는 브라우저화면에서 특정(sample1.js - sample1s in DB) table의 전체데이터 조회, 키워드로 해당데이터 조회, 여러개 키워드로 조회하는 방법을 알아보겠습니다. (기본 다른 세팅은 이전 글에서 설명한 것으로 이미 준비되었다고 가정하고 진행하겠습니다.)
진행할 작업 내용:
- 사용할 데이터를 위한 state요소와 구성할 기본화면 준비
- App.js에서 server로 데이터요청을 위한 코드 추가
- server/server.js에서 각 요청url에 대한 처리코드 추가
데이터조회 테스트를 위한 기본준비
state에서 관리할 name, email, sample1List를 준비하고 render될 화면에서는 데이터목록이 있을 때와 없을 때의 코드를 넣어줍니다. 받아올 데이터는 배열형태로 전달되기 때문에 map메소드를 사용했으며 Search버튼과 ListAll버튼의 실행할 함수는 진행과정에서 정의해주겠습니다.
//App.js
import React, { Component } from "react";
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = {
name : '',
email : '',
sample1List : [],
}
};
componentDidMount() {
}
// 이후 추가할 코드 영역
_nameUpdate(e) {
this.setState({ name : e.target.value })
}
_emailUpdate(e) {
this.setState({ email : e.target.value })
}
render() {
const { sample1List } = this.state;
return(
<div className='App'>
<h3>Hello, You are testing React!</h3>
<h4> Sample1 List </h4>
<input type='text' maxLength='10' placeholder='검색키워드(name)' onChange={(e) => this._nameUpdate(e)} />
<input type='text' maxLength='20' placeholder='검색키워드(email)' onChange={(e) => this._emailUpdate(e)}/>
<button onClick={this._getKeywordData}>Search</button>
<button onClick={this._getData}>ListAll</button>
{sample1List.length !== 0 ?
sample1List.map( (el, key) => {
return(
<div key={key}>
<span> ID: {el.id} </span>/
<span> NAME: {el.name} </span>/
<span> EMAIL: {el.email} </span>
</div>
)
})
: <div>데이터가 없습니다.</div>}
</div>
)
};
};
export default App;
//server/server.js
const express = require('express');
const app = express();
const sequelize = require('./models').sequelize;
const bodyParser = require('body-parser');
sequelize.sync();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const {
Sample1,
Sequelize: { Op }
} = require('./models');
sequelize.query('SET NAMES utf8;');
// 이후 추가할 코드 영역
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server On : http://localhost:${PORT}/`);
})
(목록을 보여주기 위해 먼저 DB table에 데이터가 있는지 확인해주세요.)
지금 상태에서 서버와 react를 실행하면 화면에서 다음과 같이 나옵니다.
전체데이터 조회 - findAll()
ListAll버튼시 전체데이터를 요청하기 위해 App.js에 아래 코드를 추가해줍니다. 처음 화면의 모든 요소가 mount됬을 때에도 전체목록을 보여줄 것이므로componentDidMount()에도 전체목록 실행함수를 넣어줍니다.
componentDidMount() {
this._getData();
}
_getData = async () => {
const res = await axios.get('/get/data');
this.setState({
sample1List : res.data
})
}
그리고 server/server.js에서 요청받은 '/get/data'에 대한 코드를 넣어줍니다.
app.get('/get/data', (req, res) => {
Sample1.findAll()
.then( result => { res.send(result) })
.catch( err => { throw err })
})
위의 findAll()은 'SELECT FROM * sample1s'의 쿼리와 동일합니다.
그 다음 서버를 재실행하여 브라우저화면에서 잘 동작하는지 확인합니다.
키워드로 데이터검색 조회 - findAll( where : {xxx : yyy} )
이번에는 name에서 입력한 키워드로 데이터를 조회해보겠습니다. App.js에서 위에 추가한 코드에 이어 다음 코드를 넣어줍니다.
_getKeywordData = async() => {
const res = await axios('/get/keywordData', {
method : 'POST',
data : {
'name' : this.state.name
},
headers: new Headers()
});
this.setState({
sample1List : res.data
})
}
server.js에도 마찬가지로 아래 코드를 넣어주고 서버를 재실행합니다.
findAll({ where : {...}})은 'SELECT FROM * sample1s WHERE name LIKE 키워드'와 동일합니다.
app.post('/get/keywordData', (req, res) => {
Sample1.findAll({
where: { name : req.body.name }
})
.then( result => { res.send(result) })
.catch( err => { throw err })
})
여러개 키워드로 데이터 조회 - findAll({ where: {[Op.or] : [{xxx : yyy}, {xxx : yyy}]} })
name과 email키워드로 데이터를 검색하는 방법을 알아보겠습니다.
App.js에서 아래의 함수를 넣어주고 검색버튼 클릭시 새로추가한 함수를 호출하도록 onClick시 함수명을 변경합니다.
_getMultiKeywordData = async() => {
const res = await axios('/get/multiKeywordData', {
method : 'POST',
data : {
'name' : this.state.name,
'email' : this.state.email
},
headers: new Headers()
});
this.setState({
sample1List : res.data
})
}
<button onClick={this._getMultiKeywordData}>Search</button>
그리고나서 '/get/multiKeywordData'에 대한 요청처리를 위한 코드를 server.js에 추가합니다.
app.post('/get/multiKeywordData', (req, res) => {
Sample1.findAll({
where: { [Op.or]: [{ name : req.body.name }, { email : req.body.email }] }
})
.then( result => { res.send(result) })
.catch( err => { throw err })
})
Op.or은 Sequelize에서 or연산자로 데이터를 조회하기 위한 메소드입니다. or(또는)이므로 name과 email중 한개만 입력해도 해당리스트가 조회됩니다.
그럼 서버를 재실행하여 브라우저에서 확인해보겠습니다.
한 개의 데이터만 조회 - findOne( where : {xxx : yyy} )
findOne은 where조건에 따라 table레코드를 한개만 가져오는 메소드입니다. findAll로 가져올 때랑 다른 점은 findAll의 경우 배열형태로 데이터목록을 담아보내지만 findOne은 객체형태로 보낸다는 점입니다. 그래서 App.js에서 setState를 할때 sample1List를 배열형태로 한번 감싸서 코드를 작성해줍니다.
App.js에서 키워드는 name값으로 하여 아래 함수를 추가해줍니다.
_getKeywordSingleData = async() => {
const res = await axios('/get/keywordSingleData', {
method : 'POST',
data : {
'name' : this.state.name
},
headers: new Headers()
});
this.setState({
sample1List : [res.data]
})
}
<button onClick={this._getKeywordSingleData}>Search</button>
server.js에도 실행코드를 추가하고 서버를 재실행합니다.
app.post('/get/keywordSingleData', (req, res) => {
Sample1.findOne({
where: { name : req.body.name }
})
.then( result => { res.send(result) })
.catch( err => { throw err })
})
브라우저에서 확인하면 모든 리스트의 공통키워드인 단어로 검색해도 첫번째 1개의 레코드만 출력됩니다.
'React.js > Setting' 카테고리의 다른 글
7. React Sequelize로 Mysql 편리하게 사용하기 - 데이터삭제 (0) | 2020.09.07 |
---|---|
6. React Sequelize로 Mysql 편리하게 사용하기 - 데이터변경 (0) | 2020.09.06 |
4. React Sequelize로 Mysql 편리하게 사용하기 - 데이터추가 (0) | 2020.08.29 |
3. React Sequelize로 Mysql 편리하게 사용하기 - table관계표현 (0) | 2020.08.25 |
2. React Sequelize로 Mysql 편리하게 사용하기 - 테이블생성 (0) | 2020.08.25 |