Skip to Content
๐Ÿ‘€ Suspensive v3์—์„œ์˜ ๋ณ€๊ฒฝ์„ ํ™•์ธํ•˜์„ธ์š”. ๋”๋ณด๊ธฐ
๋ฌธ์„œ๋ณด๊ธฐ@suspensive/react-query<Mutation/>

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> ); };
์ˆ˜์ •๋œ ๋‚ ์งœ: