리액트&타입스크립트
api 리스트 출력하기
원코드
2023. 4. 13. 21:20
1. useEffect() 로 렌더링 할 때 api 통신해서 리스트 받아온 후 setList로 state에 저장
response.data를 콘솔에 출력해보면 아래와 같이 이중배열로 오기 때문에 response.data를 배열로 state에 저장해 map()으로 뽑아 낸 뒤 그 안에 출력하고자 하는 encData를 다시 map()으로 출력해야 한다.
{resCode: '0000', resMsg: '성공',
encData: '[{"idx":2,"proIdx":2,"name":"테스트 api","path":"/api…0413","regTime":"170549","record":"","memIdx":0}]',
dataType: ''}
const [list, SetList] = useState<any[]>([]);
useEffect(() => {
const data = {
}
const config = {
headers: {
"Content-Type": "application/json; charset=UTF-8",
"callostype": /*생략*/
}
}
const callUrl = /*생략*/
axios.post(callUrl, data,config).then(response => {
/*
전달받은 데이터를 map()으로 뽑아내기 위해서 배열로 전달
[response.data]로 보내지 않고 그냥 보내면 map()으로 뽑아낼 수 없음
JSON.parse(response.data)도 해봤는데 JSON 데이터가 아니라 오류발생함.
*/
SetList([response.data])
});
}, []);
2. 조건에 따른 출력 화면 만들기
위의 response에서 resCode가 0000 즉, 성공인 경우엔 리스트를 출력하지만, 그 외의 경우에는 리스트가 제대로 전달되지 않았거나 없는 경우이기 때문에 resCode에 따라 화면 출력을 분기해줘야 한다.
checkData라는 함수를 만들어서 response.data를 list로 전달.
map() 함수를 이용해 response.data 안에 있던 resCode와 encData를 뽑아내고, encData는 json 형식이기 때문에 파싱을 해주어야 밑에서 다시 map()함수를 이용해 리스트를 반복문으로 출력할 수 있다.
function checkData(list:any /*response.data*/) {
const resCode = list.map((data:any) => {
return data.resCode
})
const encData = list.map((data:any) => {
return JSON.parse(data.encData)
})
if(resCode === '3000') {
return <tbody><tr key={resCode}><td colSpan={6}>데이터가 없습니다</td></tr></tbody>
} else {
return (
<tbody>
{encData.map((api:any, i: any) => {
return(
<tr key="{api[0].idx}">
<td key="{api[0].proIdx}">{api[0].proIdx}</td>
<td key="{api[0].name}">{api[0].name}</td>
<td key="{api[0].path}">{api[0].path}</td>
<td key="{api[0].method}">{api[0].method}</td>
<td key="{api[0].state}">{api[0].state}</td>
<td> <button>수정</button> <button>삭제</button></td>
</tr>
)
})}
</tbody>
)
}
}
3. 화면 출력
생성한 함수를 호출한 뒤, jsx 태그를 이용해서 출력
unction ApiList() {
const [list, SetList] = useState<any[]>([]);
useEffect(() => {/*생략*/}, []);
//api 리스트 출력 화면
const tableList = checkData(list)
return (
/*생략*/
<table className ="listTable">
<thead>
<tr>
<td> 프로젝트 </td>
<td> API 이름 </td>
<td> API 주소 </td>
<td> 메소드 </td>
<td> 상태 </td>
<td> 수정/삭제 </td>
</tr>
</thead>
{tableList}
</table>
</div>
</div>
</div>
);
}
4. 전체 코드
import React, {useEffect, useState} from 'react';
import axios from "axios";
function ApiList() {
const [list, SetList] = useState<any[]>([]);
useEffect(() => {
const data = {
}
const config = {
headers: {
"Content-Type":/*생략*/,
"callostype": /*생략*/
}
}
const callUrl = /*생략*/
axios.post(callUrl, data,config).then(response => {
console.log(response.data)
SetList([response.data])
});
}, []);
const tableList = checkData(list)
return (
<div className = "apiListContent">
<div className = "apiListHeader">
<h1> API 리스트 </h1>
</div>
<div className = "apiListBody">
<div className="apiSearch">
<select name ="searchOption">
<option> API 주소 </option>
<option> API 이름 </option>
</select>
<input type="text" placeholder="검색어를 입력하세요."></input>
</div>
<div className ="apiListBar">
<div className = "filtering">
<select name ="projectName">
<option value ="0">프로젝트</option>
<option value = "1">머니트리</option>
</select>
<select name ="apiState">
<option value ="0">상태</option>
<option value = "1">개발중</option>
</select>
</div>
<div className="createApiButtonDiv"><button className ="createApiButton"> 신규생성 </button></div>
</div>
<div className ="">
<table className ="listTable">
<thead>
<tr>
<td> 프로젝트 </td>
<td> API 이름 </td>
<td> API 주소 </td>
<td> 메소드 </td>
<td> 상태 </td>
<td> 수정/삭제 </td>
</tr>
</thead>
{tableList}
</table>
</div>
</div>
</div>
);
}
function checkData(list:any) {
const resCode = list.map((data:any) => {
return data.resCode
})
const encData = list.map((data:any) => {
return JSON.parse(data.encData)
})
if(resCode === '3000') {
return <tbody><tr key={resCode}><td colSpan={6}>데이터가 없습니다</td></tr></tbody>
} else {
return (
<tbody>
{encData.map((api:any, i: any) => {
return(
<tr key="{api[0].idx}">
<td key="{api[0].proIdx}">{api[0].proIdx}</td>
<td key="{api[0].name}">{api[0].name}</td>
<td key="{api[0].path}">{api[0].path}</td>
<td key="{api[0].method}">{api[0].method}</td>
<td key="{api[0].state}">{api[0].state}</td>
<td> <button>수정</button> <button>삭제</button></td>
</tr>
)
})}
</tbody>
)
}
}
export default ApiList;
공부를 제대로 하고 만든게 아니라 억지스러운 부분이 있을지도 모르지만...일단 해냈다.