axios
HTTP 기반 통신을 지원하는 자바스크립트 라이브러리
서버와 데이터를 주고받기 위한 요청/응답 처리 라이브러리
axios 사용하려면 npm 패키지 설치해야 함
Promise와 async/await
Promise 는 비동기 처리를 수행하는 패턴을 지원하는 ES6의 기능
axios.get() 함수
GET 요청 처리
// 사용 방법
// url: 요청하는 백엔드 API 의 URL을 지정
// config: 요청 시에 지정할 설정값들
// 요청 후에는 Promise 를 리턴하며 처리가 완료된 후에는 response 객체를 응답 받음
axios.get(url, config)
// 사용 예시: Promise
const requestAPI = () => {
const url = "/api/todolist/gdhong";
axios.get(url)
.then((response) => {
console.log("# 응답 객체: ", response);
});
};
requestAPI();
// 사용 예시: async/await
const requestAPI = async () => {
const url = "/api/todolist/gdhong";
const response = await axios.get(url);
console.log("# 응답 객체: ", response);
};
requestAPI();
config: 요청 시에 사용된 config 옵션
data: 수신된 응답 데이터
headers: 백엔드 API 서버가 응답할 때 사용된 응답 HTTP 헤더
request: 서버와의 통신에 사용된 XMLHttpRequest 객체의 정보
status: 서버가 응답한 HTTP 상태 코드
statusText: 서버의 HTTP 상태를 나타내는 문자열 정보
axios.post() 함수
POST 요청 처리
주로 백엔드 API 서버로 데이터를 전달해 데이터를 추가할 때 사용
// url, config는 axios.get()의 내용과 동일
// data는 POST 요청의 HTTP Content Body로 전송할 데이터
axios.post(url, data, config)
에러 처리
axios/await, try~catch로 처리하는 코드
import axios from 'axios'
const requestAPI = async () => {
const url = "/api/todolist_log/gdhong;
try {
const response = await axios.get(url, { timeout: 900 });
console.log("# 응답 객체: ", response);
} catch (e) {
console.log("## 다음 오류가 발생했습니다.");
if (e instanceof Error) console.log(e.message);
else console.log(e);
}
};
requestAPI();
type Props= {};
const App6 = (props: Props) => {
return <h2>Console Log를 확인합니다.</h2>;
};
export default App6;
Promise, catch 이용한 코드
import axios from 'axios'
const requestAPI = async () => {
const url = "/api/todolist_long/gdhong";
axios
.get(url, { timeout: 900 })
.then((response) => {
console.log("# 응답 객체: ", response);
})
.catch((e) => {
if (e instanceof Error) console.log(e.message);
else console.log(e);
});
};
requestAPI();
type Props = {};
const App7 = (props: Props) => {
return <h2>Console Log를 확인합니다.</h2>;
};
export default App7;
async/await 는 전체 데이터를 순회하면서 순차적으로 비동기 처리를 할 때 편리
재귀 함수 등을 사용하지 않고 일반적인 for문을 사용해 순회하면 되기 때문
const requestAPI = async () => {
const todoList: Array<TodoType>;
const response = await axios.get(listUrl);
todoList = responsw.data;
console.log("# TodoList: ", todoList);
for (let i = 0; i < todoList.length; i++) {
response = await axios.get(todoUrlPrefix + todoList[i].id);
console.log(`# ${i + 1}번째 Todo: `, response.data);
}
};
12장
플럭스 아키텍처
대규모 애플리케이션에서 일관된 데이터 관리를 쉽게 하기 위해 만들어진 단방향 데이터 처리 과정을 가지는 아키텍처
상태를 필요로 하는 컴포넌트에 스토어의 상태를 연결할 수 있으며, 부모 컴포넌트에서 자식 컴포넌트로 반복적이고 계층적으로 속성을 전달하지 않아도 됨
플럭스 아키텍처는 단일 디스패처를 사용하여
모든 데이터 흐름은 단일 디스패처를 거쳐 가므로 이곳에서만 모니터링과 로깅을 하면 모든 액션의 흐름을 볼 수 있으며, 액션에 의해 상태가 어떻게 변경되어가는지 쉽게 추적할 수 있음.
리덕스
리덕스는 자바스크립트 애플리케이션을 위한 예측 가능한 상태 관리 컨테이너
UI 상태와 데이터 상태를 관리하기 위한 효과적인 도구이다.
플럭스 아키텍처를 발전시켜 복잡성을 줄이도록 설계됨
플럭스의 기능에 핫 리로딩과 시간 여행 디버깅 기능을 제공함
기존 플럭스 아키텍처는 스토어가 상태와 상태 변경 로직을 포함하고 있음.
따라서 개발 중 상태 변경 로직을 변경하면 개발 중에 상태가 초기화 되어 버림.
특징 1
반면, 리덕스의 스토어는 상태만을 가지고, 상태 변경의 기능을 리듀서 라는 요소로 분리함.
이 결과 상태 변경 로직이 개발 중에 변경되더라도 상태를 유지시킬 수 있음. ==> 핫 리로딩
특징 2
리듀서를 이용해 상태를 변경할 때 기존 상태 객체를 변경하지 않고 새로운 상태 객체를 생성한다.
불변성을 가짐. (플럭스는 ㄴㄴ)
리덕스의 불변성을 가지는 상태 변경은 시간 흐름에 따라 상태의 이력을 남김
상태의 변경 추적이 가능함.
개발 중 어느 시점의 상태로 돌아가 다시 기능을 확인할 수 있어서 디버깅에 유용함. ==> 시간 여행 디버깅xios
HTTP 기반 통신을 지원하는 자바스크립트 라이브러리
서버와 데이터를 주고받기 위한 요청/응답 처리 라이브러리
axios 사용하려면 npm 패키지 설치해야 함
Promise와 async/await
Promise 는 비동기 처리를 수행하는 패턴을 지원하는 ES6의 기능
axios.get() 함수
GET 요청 처리
// 사용 방법
// url: 요청하는 백엔드 API 의 URL을 지정
// config: 요청 시에 지정할 설정값들
// 요청 후에는 Promise 를 리턴하며 처리가 완료된 후에는 response 객체를 응답 받음
axios.get(url, config)
// 사용 예시: Promise
const requestAPI = () => {
const url = "/api/todolist/gdhong";
axios.get(url)
.then((response) => {
console.log("# 응답 객체: ", response);
});
};
requestAPI();
// 사용 예시: async/await
const requestAPI = async () => {
const url = "/api/todolist/gdhong";
const response = await axios.get(url);
console.log("# 응답 객체: ", response);
};
requestAPI();
config: 요청 시에 사용된 config 옵션
data: 수신된 응답 데이터
headers: 백엔드 API 서버가 응답할 때 사용된 응답 HTTP 헤더
request: 서버와의 통신에 사용된 XMLHttpRequest 객체의 정보
status: 서버가 응답한 HTTP 상태 코드
statusText: 서버의 HTTP 상태를 나타내는 문자열 정보
axios.post() 함수
// url, config는 axios.get()의 내용과 동일
// data는 POST 요청의 HTTP Content Body로 전송할 데이터
axios.post(url, data, config)
POST 요청 처리
주로 백엔드 API 서버로 데이터를 전달해 데이터를 추가할 때 사용
import axios from 'axios'
const requestAPI = async () => {
const url = "/api/todolist_log/gdhong;
try {
const response = await axios.get(url, { timeout: 900 });
console.log("# 응답 객체: ", response);
} catch (e) {
console.log("## 다음 오류가 발생했습니다.");
if (e instanceof Error) console.log(e.message);
else console.log(e);
}
};
requestAPI();
type Props= {};
const App6 = (props: Props) => {
return <h2>Console Log를 확인합니다.</h2>;
};
export default App6;
Promise, catch 이용한 코드
import axios from 'axios'
const requestAPI = async () => {
const url = "/api/todolist_long/gdhong";
axios
.get(url, { timeout: 900 })
.then((response) => {
console.log("# 응답 객체: ", response);
})
.catch((e) => {
if (e instanceof Error) console.log(e.message);
else console.log(e);
});
};
requestAPI();
type Props = {};
const App7 = (props: Props) => {
return <h2>Console Log를 확인합니다.</h2>;
};
export default App7;
에러 처리
axios/await, try~catch로 처리하는 코드
import axios from 'axios'
const requestAPI = async () => {
const url = "/api/todolist_log/gdhong;
try {
const response = await axios.get(url, { timeout: 900 });
console.log("# 응답 객체: ", response);
} catch (e) {
console.log("## 다음 오류가 발생했습니다.");
if (e instanceof Error) console.log(e.message);
else console.log(e);
}
};
requestAPI();
type Props= {};
const App6 = (props: Props) => {
return <h2>Console Log를 확인합니다.</h2>;
};
export default App6;
Promise, catch 이용한 코드
import axios from 'axios'
const requestAPI = async () => {
const url = "/api/todolist_long/gdhong";
axios
.get(url, { timeout: 900 })
.then((response) => {
console.log("# 응답 객체: ", response);
})
.catch((e) => {
if (e instanceof Error) console.log(e.message);
else console.log(e);
});
};
requestAPI();
type Props = {};
const App7 = (props: Props) => {
return <h2>Console Log를 확인합니다.</h2>;
};
export default App7;
'React' 카테고리의 다른 글
| [React] 리액트 개념 정리 #6 (0) | 2025.10.29 |
|---|---|
| [React] 리액트 개념 정리 #4 (0) | 2025.10.26 |
| [React] 리액트 개념 정리 #3 (0) | 2025.10.26 |
| [React] 리액트 개념 정리 #2 (0) | 2025.10.26 |
| [React] 리액트 개념 정리 #1 (0) | 2025.10.26 |