useMutation
put/create/deleteする時に使う
post時のloadingのstatusとか、errorとかの管理に便利
参考
記事
雑にしか読んでないので再読したい
useQueryとの差異で注意する点
useQueryは宣言的だったが、useMutationは手続き的
defaultの話?
キャッシュがない?
リトライしない?
再フェッチしない?
mutationによって起きた変更を、queryに反映させる方法は2つ
普通はonSuccessの中で呼ぶ
mutateを実行したときに、手動で特定のqueryをslate状態にする
別の箇所でそのデータが見られている場合は、破棄され、refetchし、画面に反映させる
細かいことを言うと、そのkeyに紐づくobjectのサイズは小さい方が良いmrsekut.icon
isLikeを更新するだけのために、userをまるごとfetchしてくることになる
activeなもののみrefetchされる
更新時にrefetchしない方法
postの結果を使えばrefetchが必要ないときはこれを使う
そのkeyを他の場所でも使っていたら、それらも更新する
場合によっては、clientの更新ロジックが増えるかもしれない
lifecycle
mutationが成功した場合
onMutate→mutation→onError→onSettled
mutationが失敗した場合
onMutate→mutation→onSuccess→onSettled
useMutationとmutateに両方にコールバックを指定できるが、
その場合、useMutationのコールバックの方が先に実行される
callbackをuseMutationに書くか、mutateに書くか
post後にcomponentがumountされた場合は、mutateのcallbackは実行されないこともある
useMutationのcallbackは必ず実行される
絶対に必須なロジックはこちらに書くと良い
queryの無効化など
UIに関するものはmutateのcallbackに書けば良い
実行後のtoastの表示など。
post直後に、ユーザーがページ遷移した場合は、componentがunmountされるので、実行されない
Options
型
TData
実行の結果
Tvariables
mutation関数の引数
mutationFn: (variables: TVariables) => Promise<TData>
Required
A function that performs an asynchronous task and returns a promise.
variables is an object that mutate will pass to your mutationFn
mutationKey: string
Optional
A mutation key can be set to inherit defaults set with queryClient.setMutationDefaults or to identify the mutation in the devtools.
onMutate: (variables: TVariables) => Promise<TContext | void> | TContext | void
Optional
This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive
Useful to perform optimistic updates to a resource in hopes that the mutation succeeds
The value returned from this function will be passed to both the onError and onSettled functions in the event of a mutation failure and can be useful for rolling back optimistic updates.
callback系
onSuccess: (data: TData, variables: TVariables, context?: TContext) => Promise<unknown> | void
Optional
This function will fire when the mutation is successful and will be passed the mutation's result.
If a promise is returned, it will be awaited and resolved before proceeding
returnする
code:ts
onSuccess: () => {
}
onError: (err: TError, variables: TVariables, context?: TContext) => Promise<unknown> | void
mutationの失敗時にロールバックする
Optional
This function will fire if the mutation encounters an error and will be passed the error.
If a promise is returned, it will be awaited and resolved before proceeding
onSettled: (data: TData, error: TError, variables: TVariables, context?: TContext) => Promise<unknown> | void
Optional
This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error
If a promise is returned, it will be awaited and resolved before proceeding
retry系
retry: boolean | number | (failureCount: number, error: TError) => boolean
Defaults to 0.
If false, failed mutations will not retry.
If true, failed mutations will retry infinitely.
If set to an number, e.g. 3, failed mutations will retry until the failed mutations count meets that number.
retryDelay: number | (retryAttempt: number, error: TError) => number
This function receives a retryAttempt integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
A function like attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000) applies exponential backoff.
A function like attempt => attempt * 1000 applies linear backoff.
useErrorBoundary: undefined | boolean | (error: TError) => boolean
Defaults to the global query config's useErrorBoundary value, which is undefined
Set this to true if you want mutation errors to be thrown in the render phase and propagate to the nearest error boundary
Set this to false to disable the behavior of throwing errors to the error boundary.
If set to a function, it will be passed the error and should return a boolean indicating whether to show the error in an error boundary (true) or return the error as state (false)
meta: Record<string, unknown>
Optional
If set, stores additional information on the mutation cache entry that can be used as needed. It will be accessible wherever the mutation is available (eg. onError, onSuccess functions of the MutationCache).
Returns
mutate: (variables: TVariables, { onSuccess, onSettled, onError }) => void
useMutationに渡したmutation関数を実行する
引数は1つしか取れないので、recordを使用すると良い
mutateAsync: (variables: TVariables, { onSuccess, onSettled, onError }) => Promise<TData>
Similar to mutate but returns a promise which can be awaited.
try/catchを使用しないとerrorがcatchされない
よくわかってないmrsekut.icon
variables: TVariables
Optional
The variables object to pass to the mutationFn.
Remaining options extend the same options described above in the useMutation hook.
If you make multiple requests, onSuccess will fire only after the latest call you've made.
status: string
Will be:
idle initial status prior to the mutation function executing.
loading if the mutation is currently executing.
error if the last mutation attempt resulted in an error.
success if the last mutation attempt was successful.
isIdle, isLoading, isSuccess, isError: boolean variables derived from status
data: undefined | unknown
Defaults to undefined
The last successfully resolved data for the query.
error: null | TError
The error object for the query, if an error was encountered.
reset: () => void
A function to clean the mutation internal state (i.e., it resets the mutation to its initial state).