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은 비동기 작업과 상태 관리를 쉽게 처리할 수 있음