From the course: TanStack Query: Efficient Data Fetching and State Management
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Handling mutation errors - TanStack Query Tutorial
From the course: TanStack Query: Efficient Data Fetching and State Management
Handling mutation errors
- [Instructor] Let's talk a bit about how we can add proper error handling to our mutations. So we want to modify our saveFavorite function first, and we're going to do something kind of funny. We'll say if Math.random < 0.3, we want to throw a new Error("Failed to save status"). I was typing my words, not what I should be typing there. Throw a new Error. That should look good. Math.random, of course, is a function, too, so let's add those parentheses at the end. So we're saying here, we want our saveFavorite function to fail 30% of the time. So we probably won't build this functionality into our actual projects, but this will demonstrate it. Now beneath our current useState, we're going to add another one. This is going to track the errorMessage and the function to update this is setErrorMessage and then we'll say useState, and then right before this, we'll add a little type annotation to say string or null, and then we'll pass null as the initial state. Alright, then we'll enhance…