Mutation
<SuspenseQuery/>
๊ฐ useSuspenseQuery๋ฅผ ๊ฐ์ Depth์์ ์ฌ์ฉํ๊ฒ ํ๋ ์ญํ ๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก <Mutation/>
๋ useMutation๋ฅผ ๊ฐ์ Depth์์ ์ฌ์ฉํ๊ธฐ ์ฝ๊ฒ ํ๊ธฐ ์ํ ์ญํ ์ ํฉ๋๋ค.
import { Mutation } from '@suspensive/react-query'
import { useSuspenseQuery } from '@tanstack/react-query'
const PostsPage = () => {
const { data: posts } = useSuspenseQuery({
queryKey: ['posts'],
queryFn: () => getPosts(),
})
return posts.map(post => (
<Mutation
key={post.id}
mutationFn={({ content }: { content: string }) => api.editPost({ postId: post.id, content })}
>
{postMutation => (
<>
<div>{post.content}</div>
{post.comments.map(comment => (
<Mutation
key={comment.id}
mutationFn={({ content }: { content: string }) => api.editComment({ postId: post.id, commentId: comment.id, content })}
>
{commentMutation => (
<div>
{postMutation.isLoading ? <Spinner/> : null}
{comment.content}
<textarea onChange={e => commentMutation.mutateAsync({ content: e.target.value })} />
</div>
)}
</Mutation>
))}
</>
)}
</Mutation>
));
}
๋๊ธฐ: useMutation๊ฐ ๋ถํ์ํ Depth๋ฅผ ๋ง๋ฆ
๊ธฐ์กด์ useMutation๋ ํ ์ด๊ธฐ ๋๋ฌธ์ PostToUseMutation, CommentToUseMutation์ ๊ฐ์ ์ปดํฌ๋ํธ๋ฅผ ๋ง๋ค๊ฒ ํฉ๋๋ค. ์ด๊ฒ์ ๋ถํ์ํ Depth๋ฅผ ๋ง๋ค๊ณ ๋ถํ์ํ ์ปดํฌ๋ํธ ์ด๋ฆ, ๋ถ๋ชจ ์ปดํฌ๋ํธ์ ๊ฒฐํฉ์ผ๋ก ์ธํด ๊ตฌ์กฐ ๋ณ๊ฒฝ์ ์ ์ฐํ์ง ์๊ณ ์ด๋ ต๊ฒ ๋ง๋ญ๋๋ค.
import { useMutation } from '@tanstack/react-query'
const PostsPage = () => {
const posts = usePosts();
return posts.map(post => <PostToUseMutation key={post.id} post={post} />);
};
// PostToUseMutation (๋ถํ์ํ ์ด๋ฆ, useMutation๋ง ์ฌ์ฉํ๋๋ก ๋ณ๊ฒฝ ํ์)
const PostToUseMutation = ({ post }: { post: Post }) => { // props๋ useMutation์ ์ฌ์ฉํ๊ธฐ ์ํด ์ ๋ฌ๋์ด์ผ ํฉ๋๋ค.
const postMutation = useMutation({
mutationFn: ({ content }: { content: string }) => api.editPost({ postId: post.id }),
});
if (postMutation.isLoading) {
return <Spinner />;
}
return (
<>
<div>{post.content}</div>
<textarea onChange={e => postMutation.mutateAsync({ content: e.target.value })} />
{post.comments.map(comment => (
<CommentToUseMutation key={comment.id} post={post} comment={comment} />
))}
</>
);
};
// CommentToUseMutation (๋ถํ์ํ ์ด๋ฆ, useMutation๋ง ์ฌ์ฉํ๋๋ก ๋ณ๊ฒฝ ํ์)
const CommentToUseMutation = ({ post, comment }: { post: Post, comment: Comment }) => { // props๋ useMutation์ ์ฌ์ฉํ๊ธฐ ์ํด ์ ๋ฌ๋์ด์ผ ํฉ๋๋ค.
const commentMutation = useMutation({
mutationFn: ({ content }: { content: string }) => api.editComment({ postId: post.id, commentId: comment.id, comment }),
});
return (
<div>
{comment.content}
<textarea onChange={e => commentMutation.mutateAsync({ content: e.target.value })} />
</div>
);
};
์์ ๋ ๋ ์ง: