티스토리 뷰
반응형
데이터를 DB에서 가져와서 검색 조건에 맞게 조회하는 화면을 구상하다보면 조건에 맞춰서 다시 조회를 해야하나 싶지만 페이지 렌더링시 전체 데이터 조회, 그 후 Filter() 함수 를 사용하여 필터링하면 DB에 다시 조회할 필요가 없습니다.
Filter() 함수를 사용하여 DB에서 가져온 데이터들을 검색조건 적용시키는 방법입니다.
저는 filesData라는 배열에 검색 키워드가 filename 또는 keyword에 포함되면 일치하도록 해놨습니다.
값이 포함된지 체크하는 함수는 기존에는 indexOf()를 사용했지만, ES6 문법에서 추가된 includes() 함수를 사용했습니다.
includes() 함수는 대소문자를 구별합니다.
대소문자 상관없이 하고싶으신분들은 toLowCase()나 toUpperCase() 함수를 사용하여 검색어 및 데이터를 맞춰주시면 됩니다.
#filesData의 keyword에 test가 포함되어 있는지
console.log(filesData.keyword.includes('test'));
//true or false 반환
#filesData의 keyword에 5번째 위치부터 test가 포함되어있는지
console.log(filesData.keyword.includes('test',5));
//true or false 반환
searchKeyword의 기본값을 ""을 해놓은 이유는 ""으로 설정해줘야 검색 후, 검색값을 다 지웠을때 전체조회가 됩니다.
/*=====================JS==============*/
const [filesData, setFilesData] = useState(); //조회 결과 저장
const [searchKeyword, setSearchKeyword] = useState(""); //조회 검색어
//Page Loading Data 조회
useEffect(()=>{
axios
.post(`INSERT RESTAPI PATH`, {
/*body 부분*/
},{header})
.then((response) => {
//데이터가 넘어온 경우 저장
if(response.data){
setFilesData(response.data);
}
})
.catch((err) => {
alert("에러 발생 : "+ err)
});
},[])
/*==================JSX==============*/
/*검색 창 부분*/
<div className="div-wrap-searchCode">
<input
className="input-search"
type="text"
maxLength="25"
placeholder="파일명 또는 태그명을 입력해주세요"
onChange={(e) => {
setSearchKeyword(e.target.value);
}}
/>
</div>
/*조회 데이터 보여주기*/
<div style={{ width: "80%" }}>
//filesData가 있는 경우에만 동작하도록
{filesData
? filesData
.filter(
(searchData) =>
searchKeyword === ""
? true
: (searchData.filename
? searchData.filename.includes(searchKeyword)
: false) ||
(searchData.keyword ? searchData.keyword.includes(searchKeyword) : false)
)
.map((data,index) => {
return (
<>
{createID === "public" ? (
<div className="div-mdlSample">
<td className="div-mdlContents">
<p className="mdl-title">{data.filename}</p>
<span className="mdl-contents">Uploader: {data.createid}</span>
<span className="mdl-contents">Upload Date: {data.createtm}</span>
<span className="mdl-contents">설명: {data.explanation}</span>
<span className="mdl-contents">태그: {data.keyword}</span>
</td>
<td className="mdl-classification" style={{ width: "20%" }}>
<span className="mdl-classification">{data.algorithm}</span>
<Button
className="btn-download"
onClick={() => {
onClickHandler(data.fileid);
}}
>
Download
</Button>
</td>
</div>
) : null}
</>
);
})
: null}
</div>
반응형
'Web' 카테고리의 다른 글
[React] Sweet Alert, 이쁜 알림창 띄우기 (0) | 2022.05.25 |
---|---|
[React] FormData()사용 file 및 json, array 데이터 보내기 (0) | 2022.05.10 |
[React] ID 기억하기 cookie에 값 저장 (react-cookie) (0) | 2022.05.07 |
[React]react-spinners를 사용한 Loading 창 만들기(Modal 안에 Loading 창 넣기) (0) | 2022.05.05 |
[React] base64로 여러 장의 이미지를 서버로 전송 (0) | 2022.05.04 |
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- PoolCluster : Error: connect ECONNREFUSED 127.0.0.1:3306)
- mysql date
- AWS #인바운드 #SSH #인스턴스 연결
- 이미지 전송 # 이미지 업로드 #이미지 여러장 #이미지 여러장 업로드 #react 이미지 업로드 #react 이미지 여러장 업로드
- PDF #pdfkit
- FormData #FormData 파일전송 #FormData append json # React FormData File #React FormData append Json
- Express multer #Express File 저장 #node.js
- reack-cookies #아이디 저장하기 #react 아이디 저장 #react cookie #리엑트 아이디 저장하기
- docker # docker build # m1 docker build
- mysql date type
- ec2 instance connect is unable to connect to your instance. ensure your instance network settings are configured correctly for ec2 instance connect. for more information
- JavaScript #Programmers #lvl2 #프로그래머스 오픈채팅방 # 오픈채팅방 문제
- Swal #sweetalert2 #alert #알림창 띄우기 #react swal
- docker mysql
- supported: linux/amd64
- linux/amd64/v2
- Mac docker.for.mac.host.internal
- mysql date between performance
- Pytorch #Yolov5 #Segementation
- ERROR: failed to solve: no support for running processes with linux/amd64/v3 platform
- mysql date between # mysql date between 대소 비교 연산자
- node.js 파일 저장
- see ec2 instance connect prerequisites at https://docs.aws.amazon.com/awsec2/latest/userguide #인스턴스 연결 안됨
- node.js #node.js pdf만들기 #node.js pdfkit
- React filter #js Includes #React Filter includes
- react #react-spinners #modal loading #overlay #로딩창 #react 로딩창 만들기
- react #img 전송
- excel 파일 만들기 #node.js #express excel 파일 만들기 #데이터 입력해서 excel 파일 만들기
- BOJ #JS
- Procedure #mysql #mysql Procedure #mysql 반복문 #Procedure 반복문 #mysql insert 반복문
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함