// callback 을 사용할 때,axios.get("url").then(response=>{// response }).catch(error=>{// 오류발생시 실행}).then(()=>{// 항상 실행 혹은 finally() 사용});// async await 함수를 사용할 때, try{const data =await axios.get("url");}catch{// 오류 발생시 실행}
axios.get("url",{params:{id:123}}).then(response=>{// response }).catch(error=>{// 오류발생시 실행}).then(()=>{// 항상 실행});// async await 함수를 사용할 때, try{const data =await axios.get("url",params:{id:123});}catch{// 오류 발생시 실행}
axios.post("url",{username:"",password:""}).then(response=>{// response }).catch(error=>{// 오류발생시 실행}).then(()=>{// 항상 실행});// async await 함수를 사용할 때, try{const data =await axios.post("url",{username:"",password:""});}catch{// 오류 발생시 실행}
axios.put("url",{username:"",password:""}).then(response=>{// response }).catch(error=>{// 오류발생시 실행}).then(()=>{// 항상 실행});// async await 함수를 사용할 때, try{const data =await axios.put("url",{username:"",password:""});}catch{// 오류 발생시 실행}
axios.delete('/user?ID=12345').then(response=>{// handle success console.log(response);}).catch(error=>{// handle error console.log(error);}).then(()=>{// always executed});// async await 함수를 사용할 때, try{const data =await axios.delete("url");}catch{// 오류 발생시 실행}
axios.delete('/user?ID=12345',{data:{post_id:1,comment_id:5,username:"april"}}).then(response=>{// handle success console.log(response);}).catch(error=>{// handle error console.log(error);}).then(()=>{// always executed});// async await 함수를 사용할 때, try{const data =await axios.delete("url");}catch{// 오류 발생시 실행}
// API.js// axios 의 인스턴스를 생성import axios from'axios';constAPI= axios.create({BASE_URL:'',headers:{'Content-Type':'application/json',},withCredentials:true,});exportdefaultAPI;
importAPIfrom'../utils/API';exportconstlogin=async(code)=>{const{ data }=awaitAPI.post('url',JSON.stringify(code)// JSON 형식을 문자열로 변환);return data;}
importAPIfrom'../utils/API';exportconstrefresh=async()=>{try{const{ data }=awaitAPI.get('url');return data;}catch{// Error Handling}};
import React,{ useState, useEffect }from'react';import axios from'axios';functionUsers(){const[users, setUsers]=useState(null);const[loading, setLoading]=useState(false);const[error, setError]=useState(null);constfetchUsers=async()=>{try{// 요청이 시작 할 때에는 error 와 users 를 초기화하고setError(null);setUsers(null);// loading 상태를 true 로 바꿈setLoading(true);const response =await axios.get('https://jsonplaceholder.typicode.com/users');setUsers(response.data);// 데이터(state)는 response.data안에 들어있음}catch(e){setError(e);}setLoading(false);// 로딩이 끝났으니 false로 변경};useEffect(()=>{// 컴포넌트가 처음 마운트 된 후 실행fetchUsers();},[]);if(loading)return<div>로딩중..</div>;// 만약 loading이 True이면if(error)return<div>에러가 발생했습니다</div>;// 만약 error가 True이면// 아직 users가 받아와 지지 않았을 때는 아무것도 표시되지 않도록 해줌if(!users)returnnull;// 위의 로직에 아무것도 걸리지 않았다면 users가 성공적으로 받아와 진 상태return(<><ul>{users.map(user=>(<likey={user.id}>{user.username} ({user.name})
</li>))}</ul>{/* button을 클릭하면 API를 다시 불러와줌 */}<buttononClick={fetchUsers}>다시 불러오기<button></> );
}
export default Users;
functionreducer(state, action){switch(action.type){// 발생할 수 있는 상황 LOADING, SUCCESS, ERROR에 대한 case를 만들어줌// 로딩중 상태 업데이트case'LOADING':return{loading:true,data:null,error:null};// 불러오는데에 성공했을 때는 action.data를 저장해줌case'SUCCESS':return{loading:false,data: action.data,error:null};// 에러가 발생하면 action.error를 전달해줌case'ERROR':return{loading:false,data:null,error: action.error
};default:// 아무 액션도 주어지지 않으면thrownewError(`Unhandled action type: ${action.type}`);}
functionUsers(){// reducer 함수의 전달과 초기상태를 정의합니다.const[state, dispatch]=useReducer(reducer,{loading:false,data:null,error:null});constfetchUsers=async()=>{//시작할 때 로딩중인 상태를 만들어줍니다.dispatch({type:'LOADING'});try{const response =await axios.get('https://jsonplaceholder.typicode.com/users');dispatch({type:'SUCCESS',data: response.data });}catch(e){dispatch({type:'ERROR',error: e });}};useEffect(()=>{fetchUsers();},[]);// state.data 를 users 키워드로 조회const{ loading,data: users, error }= state;if(loading)return<div>로딩중..</div>;if(error)return<div>에러가 발생했습니다</div>;if(!users)returnnull;return(<><ul>{users.map(user=>(<likey={user.id}>{user.username} ({user.name})
</li>))}</ul><buttononClick={fetchUsers}>다시 불러오기</button></>);}
import axios from'axios';constonFulfilled=(response)=>{// HTTP status가 2XX일 때 처리하고 싶은 로직이 있다면 여기에서 처리함// 데이터 받기에 성공했으므로 받은 response를 그대로 return 해준다.// 물론 따로 가공해도 됩니다.return response;};constonRejected=(error)=>{// HTTP status가 2XX이 아닐 때 여기를 통과하게 됨// return은 항상 Promise.reject(error)로 해야함return Promise.reject(error);};axios.interceptors.response.use(onFulfilled, onRejected);// 미들웨어 형식으로 선언