Michal Kurz
Michal Kurz

Reputation: 2095

How to reset RTKQuery mutation state back to `uninitiated` inside a thunk?

I have a RTKQuery mutation for submitting data to server, which uses fixedCacheKey. I manipulate it via .initiate() function within thunks:

dispatch(
  commentsApi.endpoints.updateComment.initiate(
    { commentId, patch },
    { fixedCacheKey: getFixedCacheKey(commentId) }
  )
)

I am looking for a way to programatically reset its state back to status: "uninitialized" inside my custom thunk action.

There there is a "reset" function returned by useMutation hook, which seems to do exactly what I want - but I want it done inside a thunk - something like:

// This does not work (commentsApi.endpoints.updateComment.reset is not a function)
dispatch(
  commentsApi.endpoints.updateComment.reset({ 
    fixedCacheKey: getFixedCacheKey(commentId) 
  })
)

How can I make this reality? :)

Upvotes: 0

Views: 771

Answers (1)

phry
phry

Reputation: 44236

That reset is also on the object you get from dispatching initiate:

const runningMutation = dispatch(
  commentsApi.endpoints.updateComment.initiate(
    { commentId, patch },
    { fixedCacheKey: getFixedCacheKey(commentId) }
  )
)


// later
runningMutation.reset()

you just need to save that variable to the side.

You can also use api.internalActions.removeMutationResult({ requestId }) or api.internalActions.removeMutationResult({ fixedCacheKey }), but that is an implementation detail and might change in the future.

Upvotes: 1

Related Questions