Axios로 POST, PUT 및 DELETE 사용하기
Axios의 POST와 PUT으로 API에 데이터를 보내고 응답을 처리해 로컬 상태를 업데이트하며, 서버와 목록 양쪽에서 항목을 삭제하는 작업을 구현합니다.
Axios로 POST, PUT 및 DELETE 사용하기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
CRUD Operations with Axios
Beyond fetching data, most apps need to create, update, and delete resources on a server. Axios provides axios.post, axios.put, axios.patch, and axios.delete methods that map directly to HTTP verbs. Each method returns a Promise resolving to the server's response.
POST: Creating a New Resource
axios.post(url, data) sends a request body as JSON to create a new resource. The second argument is the request body object — Axios automatically serializes it to JSON and sets the Content-Type: application/json header. The server typically responds with the created resource including its assigned ID.
const createPost = async (title, body) => {
const response = await axios.post(
'https://jsonplaceholder.typicode.com/posts',
{ title, body, userId: 1 }
);
console.log('Created:', response.data);
// { id: 101, title: '...', body: '...', userId: 1 }
return response.data;
};Adding a New Item to State After POST
After a successful POST, add the returned item to your local state array to reflect the creation without a full re-fetch. Use the functional form of setState to safely merge the new item with the existing array. The server-assigned ID is used as the unique key in subsequent renders.
const handleCreate = async (formData) => {
try {
const response = await axios.post('/posts', formData);
const newPost = response.data;
setPosts((prev) => [newPost, ...prev]);
} catch (err) {
setError('Failed to create post');
}
};PUT: Replacing a Full Resource
axios.put(url, data) replaces an entire resource with the provided data. Include the resource's ID in the URL and send all fields in the body. PUT is idempotent — calling it multiple times with the same data produces the same result. Use PUT when you are replacing the complete resource, not just updating a few fields.
const updatePost = async (postId, updatedData) => {
const response = await axios.put(
'/posts/' + postId,
updatedData
);
return response.data;
};PATCH: Partial Update
axios.patch(url, data) sends only the changed fields instead of the entire resource. This is more efficient than PUT when you are updating a single field (like a user's avatar or a post's title). Many REST APIs support both PUT and PATCH — check the API documentation to see which one is expected.
// Only update the title, leave other fields untouched
const patchPostTitle = async (postId, newTitle) => {
const response = await axios.patch(
'/posts/' + postId,
{ title: newTitle }
);
return response.data;
};Updating State After PUT/PATCH
After a successful update, replace the old item in the state array with the server's returned version. Use Array.map to iterate over the state and swap the matching item. This keeps the local state in sync with the server without a full re-fetch.
const handleUpdate = async (postId, updatedData) => {
try {
const response = await axios.put('/posts/' + postId, updatedData);
const updatedPost = response.data;
setPosts((prev) =>
prev.map((p) => (p.id === postId ? updatedPost : p))
);
} catch (err) {
setError('Failed to update post');
}
};DELETE: Removing a Resource
axios.delete(url) removes the resource at the given URL. Most APIs return a 200 or 204 (No Content) response on successful deletion. Unlike POST and PUT, DELETE does not send a request body. The third argument to axios.delete can pass config options like auth headers.
const deletePost = async (postId) => {
await axios.delete('/posts/' + postId);
console.log('Post deleted');
};Removing the Item from State After DELETE
After a successful DELETE, filter the item out of your local state array with Array.filter. The UI updates immediately without a round-trip to re-fetch the full list. If the DELETE fails, the error is caught and the item remains in state — showing the user an error message.
const handleDelete = async (postId) => {
try {
await axios.delete('/posts/' + postId);
setPosts((prev) => prev.filter((p) => p.id !== postId));
} catch (err) {
setError('Failed to delete post');
}
};Optimistic Updates
Optimistic updates update the local state immediately (before the server confirms) to make the UI feel instant. If the request fails, revert to the original state and show an error. This pattern is used by Twtter's like button and Gmail's delete — the action feels instant even over a slow connection.
const handleDelete = async (postId) => {
const originalPosts = posts;
// Update immediately
setPosts((prev) => prev.filter((p) => p.id !== postId));
try {
await axios.delete('/posts/' + postId);
} catch (err) {
// Revert on failure
setPosts(originalPosts);
setError('Delete failed. Please try again.');
}
};Uploading Files with FormData
To upload an image or file via POST, create a FormData object, append the file using the React Native URI format, and pass it to axios.post. Set the Content-Type header to multipart/form-data so the server parses it correctly as a file upload rather than JSON.
const uploadAvatar = async (imageUri) => {
const formData = new FormData();
formData.append('avatar', {
uri: imageUri,
name: 'avatar.jpg',
type: 'image/jpeg',
});
const response = await axios.post('/user/avatar', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return response.data.avatarUrl;
};Chaining Mutations: Create Then Navigate
After a successful POST or PUT, you often want to navigate the user to the newly created resource's detail screen. Chain the navigation call after the state update in the success path of your try/catch. Pass the new resource's ID or the full object as navigation params.
const handleCreatePost = async (formData) => {
try {
const response = await axios.post('/posts', formData);
const newPost = response.data;
setPosts((prev) => [newPost, ...prev]);
navigation.navigate('PostDetail', { postId: newPost.id });
} catch (err) {
setError('Failed to create post');
}
};Quick Check
Test your understanding of POST, PUT, and DELETE requests with Axios from this lesson.
Lesson Recap
In this lesson you learned: axios.post sends a JSON body to create a resource and returns the created item from the server, axios.put/patch replaces or partially updates a resource — update state with Array.map after success, and axios.delete removes a resource — update state with Array.filter and use optimistic updates for a snappy UX. Next up we explore Redux Toolkit for managing complex application state.
자주 묻는 질문
“Axios로 POST, PUT 및 DELETE 사용하기” 강의는 무료인가요?
네 — “Axios로 POST, PUT 및 DELETE 사용하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“Axios로 POST, PUT 및 DELETE 사용하기”에서 뭘 배우나요?
Axios의 POST와 PUT으로 API에 데이터를 보내고 응답을 처리해 로컬 상태를 업데이트하며, 서버와 목록 양쪽에서 항목을 삭제하는 작업을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“Axios로 POST, PUT 및 DELETE 사용하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- useEffect 훅과 의존성 배열
- Axios로 GET 요청 보내기
- 로딩 및 오류 상태 처리
- Axios로 POST, PUT 및 DELETE 사용하기