React

[TIL/React] 2024/09/06

✅ API Reference - useMutationState MutationCache에 존재하는 모든 mutation에 접근할 수 있도록 하는 hook이다. 1)filter를 통해 mutation을 좁힐 수 있고, 2)select를 통해 mutation의 상태를

2024년 9월 6일6min read

✅ API Reference - useMutationState

MutationCache에 존재하는 모든 mutation에 접근할 수 있도록 하는 hook이다.

1)filter를 통해 mutation을 좁힐 수 있고, 2)select를 통해 mutation의 상태를 변환할 수 있다.

각각이 무엇을 의미하는지 정리하도록 하겠다.

Example 1 ✍️

Get all variables of all running mutations```

import { useMutationState } from '@tanstack/react-query'

const variables = useMutationState({ filters: { status: 'pending' }, select: (mutation) => mutation.state.variables, })

code

filter와 select를 통해, 현재 진행 중인 모든 Mutation의 변수들을 가져오는 방법에 관한 공식문서 예제



## Example 2 ✍️
code
import { useMutation, useMutationState } from '@tanstack/react-query'

const mutationKey = ['posts']

// Some mutation that we want to get the state for
const mutation = useMutation({
  mutationKey,
  mutationFn: (newPost) => {
    return axios.post('/posts', newPost)
  },
})

const data = useMutationState({
  // this mutation key needs to match the mutation key of the given mutation (see above)
  filters: { mutationKey },
  select: (mutation) => mutation.state.data,
})

mutationKey를 통해, 특정 mutation에 대한 모든 데이터를 가져오는 방법에 관한 공식문서 예제

Example 3 ✍️

Access the latest mutation data via the mutationKey Each invocation of mutate adds a new entry to the mutation cache for gcTime milliseconds.```

import { useMutation, useMutationState } from '@tanstack/react-query'

const mutationKey = ['posts']

// Some mutation that we want to get the state for const mutation = useMutation({ mutationKey, mutationFn: (newPost) => { return axios.post('/posts', newPost) }, })

const data = useMutationState({ // this mutation key needs to match the mutation key of the given mutation (see above) filters: { mutationKey }, select: (mutation) => mutation.state.data, })

// Latest mutation data const latest = data[data.length - 1]

code

mutationKey를 통해 최신 Mutation 데이터에 접근하는 방법에 관한 공식문서 예제

useMutationState가 반환하는 배열의 마지막 항목에 접근한다는 의미이다.


## 예제 코드 ✍️

import React from "react"; import { useQuery, useMutation, useMutationState } from "@tanstack/react-query"; import axios from "axios";

// Fetch 'posts/users' using jsonplaceholder const fetchPosts = async () => { const { data } = await axios.get( "https://jsonplaceholder.typicode.com/posts" ); return data; };

const fetchUsers = async () => { const { data } = await axios.get( "https://jsonplaceholder.typicode.com/users" ); return data; };

// Add a new 'post/user' mutation const addPost = async (newPost) => { const { data } = await axios.post( "https://jsonplaceholder.typicode.com/posts", newPost ); return data; };

const addUser = async (newUser) => { const { data } = await axios.post( "https://jsonplaceholder.typicode.com/users", newUser ); return data; };

const App = () => { // Fetch posts using useQuery const { data: posts, isLoading: isPostsLoading } = useQuery({ queryKey: ["posts"], queryFn: fetchPosts, });

// Fetch users using useQuery const { data: users, isLoading: isUsersLoading } = useQuery({ queryKey: ["users"], queryFn: fetchUsers, });

// Create a post mutation const postMutation = useMutation({ mutationKey: ["posts"], mutationFn: addPost, });

// Create a user mutation const userMutation = useMutation({ mutationKey: ["users"], mutationFn: addUser, });

// Example 1 ✍️: Get all variables of all running mutations (both posts and users) const pendingMutations = useMutationState({ filters: { status: "pending" }, select: (mutation) => mutation.state.variables, });

// Example 2 ✍️: Get all data for specific mutations (posts) const postsMutationState = useMutationState({ filters: { mutationKey: ["posts"] }, select: (mutation) => mutation.state.data, });

// Example 2 ✍️: Get all data for specific mutations (users) const usersMutationState = useMutationState({ filters: { mutationKey: ["users"] }, select: (mutation) => mutation.state.data, });

// Example 3 ✍️: Access the latest mutation data for posts const latestPostMutation = postsMutationState?.[postsMutationState.length - 1];

// Example 3 ✍️: Access the latest mutation data for users const latestUserMutation = usersMutationState?.[usersMutationState.length - 1];

if (isPostsLoading || isUsersLoading) { return

Loading...
; } console.log({ "1.pendingMutations": pendingMutations, "2.postsMutationState": postsMutationState, "3.usersMutationState": usersMutationState, "4.latestPost": latestPostMutation, "5.latestUser": latestUserMutation, });

return (

Posts

{posts?.map((post) => (

{post.title}

{post.body}

))}

{postMutation.isLoading &&

Posting...
} {postMutation.isError &&
Error occurred while posting a post.
} {postMutation.isSuccess &&
Post added successfully!
}

Users

{users?.map((user) => (

{user.name}

{user.email}

))}

{userMutation.isLoading &&

Adding user...
} {userMutation.isError &&
Error occurred while adding a user.
} {userMutation.isSuccess &&
User added successfully!
}

Pending Mutation Variables (Example 1):

{JSON.stringify(pendingMutations, null, 2)}

Latest Post Mutation Data (Example 3):

{latestPostMutation ? (

{latestPostMutation.title}

{latestPostMutation.body}

) : (
No new post mutations yet.
)}

Latest User Mutation Data (Example 3):

{latestUserMutation ? (

{latestUserMutation.name}

{latestUserMutation.email}

) : (
No new user mutations yet.
)}
); };

export default App;

code

![](https://velog.velcdn.com/images/minkwan/post/63b6e888-0d8c-42fe-9112-a63e901c9237/image.png)

다섯 가지 콘솔을 각각 주석처리를 통해 확인하면, useMutationState에 대해 쉽게 이해할 수 있다.


> **✅ API Reference - useSuspenseQuery**

useSuspenseQuery는 useQuery와 유사하지만, 특별한 목적을 갖는 hook이다.

React의 Suspense 개념을 활용하여 데이터를 로딩하는 동안 fallback UI를 표시하기 위한 목적으로 사용한다. 

useSuspenseQuery를 사용하면 로딩 상태와 데이터 상태를 처리하기 위해 별도의 로직을 작성할 필요가 없기 때문에, 코드의 가독성을 제고할 수 있다는 장점이 있다.

## 기본 형태 ✍️

const result = useSuspenseQuery(options)

code

## Options ✍️

1. ```throwOnError```: 오류가 발생했을 때, 예외를 던질지 여부를 설정한다. 기본값은 true이고, React의 error boundary에서 해당 오류를 잡아서 처리할 수 있다.

2. ```enabled```: useSuspenseQuery에서는 사용 불가능하다.

3. ```placeholderData```:  useSuspenseQuery에서는 사용 불가능하다. 데이터 로딩 중에는 기본적으로 suspense의 fallback UI가 표시된다.

## Returns ✍️

1. ```data```: 쿼리의 데이터가 포함된다. useSuspenseQuery는 데이터가 항상 정의되어 있음을 보장하므로, data는 항상 유효한 값을 갖게 된다.

2. ```isPlaceholderData```: useSuspenseQuery에서는 사용 불가능하다.

3. ```status```: 쿼리의 상태를 나타낸다. useSuspenseQuery에서는 상태가 항상 success로 설정되며, 데이터 로딩 중에는 fallback UI를 표시한다.


## 예제 코드 ✍️

import React, { Suspense } from "react"; import { useSuspenseQuery } from "@tanstack/react-query"; import axios from "axios"; import styled from "styled-components";

// Fetch posts using jsonplaceholder const fetchPosts = async () => { const { data } = await axios.get( "https://jsonplaceholder.typicode.com/posts" ); return data; };

// Styled-components for the loading UI const FallbackContainer = styled.div` display: flex; align-items: center; justify-content: center; height: 100vh; background: #f0f0f0; `;

const Loader = styled.div` border: 8px solid #f3f3f3; border-radius: 50%; border-top: 8px solid #3498db; width: 60px; height: 60px; animation: spin 1.5s linear infinite;

@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } `;

const PostsList = () => { // Using useSuspenseQuery const { data: posts } = useSuspenseQuery({ queryKey: ["posts"], queryFn: fetchPosts, throwOnError: true, });

return (

Posts

{posts.map((post) => (

{post.title}

{post.body}

))}
); };

const App = () => { return ( } > ); };

export default App;

code
![](https://velog.velcdn.com/images/minkwan/post/7de832b8-930d-4eea-bf0c-0b79ca622a3b/image.png)

네트워크를 3G로 변경하여 fallback UI가 제대로 작동하는지 테스트했다.


> **✅ Tanstack Query 정리**

살펴본 API

1. useQuery
2. useQueries
3. useInfiniteQuery
4. useMutation
5. useIsFetching
6. useIsMutating
7. useMutationState
8. useSuspenseQuery

이 정도면, 나머지는 필요할 때 적용하면 되겠다는 생각이 들어서 tanstack-query는 여기서 마치겠다. 

reference: https://www.youtube.com/watch?v=n-ddI9Lt7Xs&t=551s