일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 오공완
- 리액트
- 클래스 추가하기 #특정 url 클래스 추가 #사이트 접속시 클래스 추가 #오공완 #javascript
- map()에는 key값이 필요
- 리스트랜더링
- React
- 오공완 #리액트 공부 #React
- Today
- Total
new_bird-hyun
Redux Toolkit Query로 Mutation 구현하기 본문
// store.js
import { configureStore } from '@reduxjs/toolkit';
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const postsApi = createApi({
reducerPath: 'postsApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://jsonplaceholder.typicode.com' }),
endpoints: (builder) => ({
getPosts: builder.query({
query: () => '/posts',
}),
addPost: builder.mutation({
query: (newPost) => ({
url: '/posts',
method: 'POST',
body: newPost,
}),
}),
deletePost: builder.mutation({
query: (id) => ({
url: `/posts/${id}`,
method: 'DELETE',
}),
}),
}),
});
export const { useGetPostsQuery, useAddPostMutation, useDeletePostMutation } = postsApi;
const store = configureStore({
reducer: {
[postsApi.reducerPath]: postsApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(postsApi.middleware),
});
export default store;
// App.js
import React, { useState } from 'react';
import { useGetPostsQuery, useAddPostMutation, useDeletePostMutation } from './store';
import { Provider } from 'react-redux';
import store from './store';
function Posts() {
const { data: posts, error, isLoading } = useGetPostsQuery();
const [addPost] = useAddPostMutation();
const [deletePost] = useDeletePostMutation();
const [newPost, setNewPost] = useState('');
const handleAddPost = async () => {
await addPost({ title: newPost, body: 'This is a new post', userId: 1 });
setNewPost('');
};
const handleDeletePost = async (id) => {
await deletePost(id);
};
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>Posts</h1>
<input
type="text"
value={newPost}
onChange={(e) => setNewPost(e.target.value)}
placeholder="New post title"
/>
<button onClick={handleAddPost}>Add Post</button>
<ul>
{posts.map((post) => (
<li key={post.id}>
{post.title}{' '}
<button onClick={() => handleDeletePost(post.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
function App() {
return (
<Provider store={store}>
<Posts />
</Provider>
);
}
export default App;
// Redux Toolkit Query의 Mutation은 비동기 작업과 상태 관리를 쉽게 처리할 수 있음
'코딩 공부' 카테고리의 다른 글
React에서 Context API와 Selector로 성능 최적화 (1) | 2024.12.31 |
---|---|
React에서 Optimistic Updates 구현하기 (0) | 2024.12.30 |
Redux Toolkit Query를 활용한 데이터 패칭 (1) | 2024.12.26 |
Redux Toolkit의 Thunk를 사용한 비동기 상태 관리 (1) | 2024.12.24 |
React와 Redux Toolkit으로 상태 관리하기 (0) | 2024.12.23 |