React Native로 프로젝트를 개발하며 REST API를 활용한 경험을 정리하기위해 이번 글에서는 "식사" 카테고리 기능 구현을 위한 REST API 연동 과정을 기록한다~
REST API는 Representational State Transfer(REST) 아키텍처 스타일을 따르는 API입니다. HTTP 메서드와 명확한 URL 구조를 사용하여 데이터를 교환하며, 상태 비저장(Stateless) 방식으로 동작합니다.
HTTP 메서드: GET, POST, PUT, DELETE 등을 사용하여 자원을 CRUD(생성, 읽기, 수정, 삭제)합니다.
URL 구조: 자원(Resource)을 명확히 표현하는 경로를 사용합니다.
상태 비저장: 각 요청은 독립적으로 처리되며, 서버는 이전 요청의 상태를 저장하지 않습니다. -> http 이기 때문에 stateless이다!
먼저 axios 라이브러리를 다운받는다.
npx install axios
식사: http:/서버/api/careCalendar/meal
휴식: http://서버/api/careCalendar/rest
이 두 엔드포인트로 서버에 데이터를 저장하고 요청한다.
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('http://서버/api/careCalendar/meal');
console.log('Server Response:', response.data);
const data = response.data.calendar;
setTitle(data.title);
setDate(data.date);
setMealType(response.data.mealType); // 식사 유형 설정
} catch (error) {
console.error('Failed to fetch data:', error);
}
};
fetchData();
}, []);
axios.get으로 데이터를 가져오며, 성공 시 서버의 응답 데이터를 상태(state)에 저장한다.
Server Response: {"calendar": {"careAssignment": null, "careAssignmentId": null, "careAssignments": [[Object], [Object]], "category": "meal", "date": null, "endTime": null, "eventType": null, "hospital": null, "id": null, "isAlarm": null, "isAllday": null, "isShared": null, "location": null, "meal": null, "medications": [], "memo": null, "myCalendar": null, "others": [], "repeatCycle": null, "rest": null, "startTime": null, "title": null}, "mealType": ["아침", "점심", "저녁", "기타"]}
로그를 보면 데이터는 JSON 형식으로 반환된다.
const handleRegister = async () => {
const payload = {
title,
date,
startTime: "10:00:00",
endTime: "14:00:00",
mealType: meal,
category: "meal",
};
try {
const response = await axios.post('http://서버/api/careCalendar/meal', payload);
console.log('Successfully posted data:', response.data);
navigation.replace('HomeScreen'); // 성공 시 화면 이동
} catch (error) {
console.error('Error posting data:', error);
}
};
payload는 서버로 보낼 JSON 데이터이다.
axios.post는 이 데이터를 POST 방식으로 서버에 전송하고 요청이 성공하면 서버에 로그가 잘 찍히는걸 볼 수 있다!
각 컴포넌트에서 useState를 사용해 데이터를 관리해줬다.
const [title, setTitle] = useState('');
const [date, setDate] = useState('');
const [mealType, setMealType] = useState([]);
api로 받은 데이터들은 다시 하위 컴포넌트 input으로 들어가 UI에 반영이 된다. 따라서 데이터 관리는 상위 컴포넌트에서 해주는게 제일 좋다