비동기방식으로 페이지를 다시 로드하지 않고 서버에 요청할 수 있게 해준다.
yarn을 사용한다면 yarn add axios
npm을 사용한다면 npm install axios
import axios from 'axios'
API_URL = "주소"
axios.get(API.URL)
.then( (res)=> {
//function1
console.log(res.data)
setData[...Data, ...res.data]
})
.catch( (err)=> {
//function 2
console.log(err)
})
function1은 axios.get 요청이 성공했을때 //.then
가져온 데이터를 기존 state에 추가할때는 직접 변경하면 안되고
기존의 데이터를 딥카피해서 수정후 사용한다.
function2는 요청이 실패 했을때 //.catch
실행된다.
axios는 json을 가져와서 object로 바꿔준다.
API_URL = "주소"
fetch.get(API.URL)
.then( (res)=> {
//function1
console.log(res)
})
.catch( (err)=> {
//function 2
console.log(err)
})
fetch()는 호환성이 상대적으로 좋지않고
json을 그대로 가져오기때문에 object로 변환해주는 과정이 필요하다.