Minor RTK mutation function call fix
weixin-tan opened this issue · 1 comments
What docs page needs to be fixed?
- Section: Redux Essentials
- Page: Part 8 RTK Query Advanced Patterns
What is the problem?
Seems like a minor typo/missing function call in the usage of mutation function. In part 7, it is stated that the .unwrap()
function needs to be called for the RTK mutation query.
As with the thunk dispatch, we call addNewPost with the initial post object. This returns a special Promise with a .unwrap() method, and we can await addNewPost().unwrap() to handle any potential errors with a standard try/catch block.
Whereas in part 8 code snippet for Editing Post, the .unwrap()
call is missing for a very similar mutation function.
const [updatePost, { isLoading }] = useEditPostMutation()
/* code omitted */
const onSavePostClicked = async () => {
if (title && content) {
await updatePost({ id: postId, title, content }) // <- this should have a .unwrap() ?
history.push(`/posts/${postId}`)
}
}
What should be changed to fix the problem?
Add .unwrap()
to the code snippet
adding unwrap is a specific choice for the call site - by default, the promise will not reject regardless of whether the request succeeded or not.
calling unwrap makes it so it will reject the promise for an unsuccessful request, which means you should be adding specific error handling (.catch or try catch) for that promise rejection.
calling a trigger without unwrapping essentially says "i don't care if the request succeeds or not, i just want to try it - I'll probably handle the failure via the hook result instead". this is a valid choice, and likely the one this example is conveying.
when you add an unwrap without handling the error it might throw, you'll end up with logged errors about an unhandled promise rejection, which is usually undesirable.