🤯TIL/React
[React] async와 await를 사용한 CRUD
Dorothy_YANG
2023. 11. 30. 00:24
728x90
1. Create (C) - 비동기적으로 데이터 생성 POST
// 예시: Axios를 사용한 POST 요청
const createData = async (data) => {
try {
const response = await axios.post('/api/data', data);
console.log(response.data); // 생성된 데이터 확인
} catch (error) {
console.error('Error creating data:', error);
}
};
2. Read (R) - 비동기적으로 데이터 조회 GET
// 초기 데이터 로딩
const fetchInitialData = async () => {
try {
const response = await axios.get('/api/data');
console.log(response.data);
} catch (error) {
console.error('Error fetching initial data:', error);
}
};
// 조회 조건에 따른 데이터 로딩
const fetchDataWithConditions = async (condition1, condition2, condition3) => {
try {
const response = await axios.get('/api/data/query', {
params: {
condition1,
condition2,
condition3,
},
});
console.log(response.data);
} catch (error) {
console.error('Error fetching data with conditions:', error);
}
};
3. Update (U) - 비동기적으로 데이터 업데이트 PUT
// 예시: Axios를 사용한 PUT 요청
const updateData = async (id, updatedData) => {
try {
const response = await axios.put(`/api/data/${id}`, updatedData);
console.log(response.data); // 업데이트된 데이터 확인
} catch (error) {
console.error('Error updating data:', error);
}
};
4. Delete (D) - 비동기적으로 데이터 삭제
// 예시: Axios를 사용한 DELETE 요청
const deleteData = async (id) => {
try {
const response = await axios.delete(`/api/data/${id}`);
console.log(response.data); // 삭제된 데이터 확인
} catch (error) {
console.error('Error deleting data:', error);
}
};
728x90