본 포스트는 Udemy 리액트 완벽가이드 2024 를 듣고 정리한 내용입니다.
목차 🌳
1️⃣ 리액트 앱을 백엔드/ DB와 연결하기
2️⃣ 데이터 fetch 방법
3️⃣ 데이터 send 방법
HTTP 요청을 보내고 응답을 받음으로써, 프론트와 서버(DB)는 연결됨
보안 이슈로 인해, 리액트 앱에서 직접적으로 서버와 데베는 연결될 수 없음
오류의 유형화
1️⃣ 요청을 보내는 것에 실패하여, 백엔드에 전달되지 못 하는 경우
2️⃣ 요청이 성공적으로 백엔드에 전달되었지만, 백엔드에서 에러 응답을 보내는 경우
일단 응답이 에러인지 아닌지 확인 후, 핸들링하기
async function fetchPlaces() {
const res = await fetch('http://localhost:3000/places');
const data = await res.json();
if(res.ok) {} // 200 ~ 300
if (!res.ok) { // 400 ~ 500
const eror = new Error ('Failed to fetch places');
throw error;
}
}
근데 이상태로 에러를 throw 하면 앱이 깨지기 때문에, 사용자에게 무척이나 좋지 못함.
try - catch문으로 에러가 발생할때 실행할 코드 작성하기
try
-> 실패할 수 있는 코드를 담고 있음
catch
-> error를 만났을때 실행할 코드를 담고 있음
또한, 에러를 다룰 수 있도록 err 상태를 관리해줘야함!!
if(err) -> 특정 UI 도출!
const [error, setError] = useState();
useEffect(() => {
setIsFetching(true);
async function fetchPlaces() {
try {
const res = await fetch('http://localhost:3000/places');
const data = await res.json();
if (!res.ok) throw new Error('Failed to fetch places');
setAvailablePlaces(data.places);
} catch (err) {
setError({ message: err.message || '장소를 못 가져왔어요' });
}
setIsFetching(false);
}
fetchPlaces();
}, []);
if (error) {
return <Error title="오류 발생!" message={error.message} />;
}
export async function updateUserPlaces(places) {
const res = await fetch('http://localhost:3000/user-places', {
method: 'PUT',
body: JSON.stringify({ places: places }),
headers: {
'Content-Type': 'application/json',
},
});
const resData = await res.json();
if (!res.ok) throw new Error('Failed to update User Place');
return resData.message;
}
fetch는 기본적으로 get 메소드를 수행하기 때문에, 요청을 보낼떄 method를 수정해서 보내줘야 한다.
그리고 body에 넣을 값을 넣어주고, 헤더엔 보낼 내용의 유형이 JSON임을 알려야 함!
기본적인 내용이기에 이만 말줄임! 🐴