배경
- api요청을 하는 함수를 따로 빼놓고, import해서 불러와서 사용함
- 근데 함수 돌아가기 전에 set어쩌구를 했더니 결과가 화면에 안나옴(= 저장이 안됨)
- 그래서 비동기를 위해 async await 사용하고자 함
- 근데 타입 지정 어떻게 해야함?
공식 문서에서는 Promise<변수 타입> 을 쓰라고 합니다.

해결한 코드
// 우선 함수가 들어있는 ts파일
import axios from "axios";
// 고민 타입
type consultType = {
consultId : number,
memberId : number,
title : string,
content : string,
categoryId : number
}
// try-catch 사용했을 때
async function getConsults(): Promise<consulttype[]> {
try {
const res = await axios.get('')
return res.data
} catch (err) {
console.log(err);
return [];
}
}
export {getConsults}
더보기
만약 여기서 try, catch가 아니라, then, catch를 쓰고 싶다면?
// then, catch 사용했을 때
function getConsults(): Promise<consultType[]> {
return axios.get('')
.then((res) => {
return res.data
})
.catch((err) => {
console.log(err)
return []
})
}
그리고 나서는 이 함수를 써야하는 파일로 이동해서 요청을 보내보자
// 우선 함수 가져와주고
import {getConsults} from './../../api/consults'
// 받을 타입도 저장해주자
type consultType = {
consultId : number,
memberId : number,
title : string,
content : string,
categoryId : number
}
// 함수 안에서
function Others() {
// 저장해서 써먹을 변수 만들어주고
const [otherConsults, setOtherConsult] = useState<consultType[]>([])
// 로드될 때 가져올 useEffect
useEffect(() => {
// 이때도 async await를 써보자
const fetchConsult = async () => {
try {
let tempOtherConsult :consultType[] = await getConsults()
setOtherConsult(tempOtherConsult)
} catch(err) {
console.log(err)
}
}
fetchConsult()
}, [])
'FrontEnd > TypeScript' 카테고리의 다른 글
[TypeScript] TypeScript 기본지식 (0) | 2024.06.28 |
---|---|
[TypeScript] 타입을 한 곳에 모아보자~~ (0) | 2024.03.22 |