The tags feature shown in this lesson is arguably RTK Query's best feature. It's conceptually simple, but incredibly powerful. If you can know ahead of time which operations will invalidate your data, then you should always refresh the data after you perform those operations.
The basic premise is that you specify which tags queries rely on with providesTags
and then which tags a mutation will invalidate with invalidatesTags
.
One of the advanced things you can do with tags, which we don't cover here is configuring mutations to invalidate tags with a specific ID. So imagine if you edit an entry, you don't want it to invalidate every other entry, just that one AND the list. This is covered in the automated refreshing section of the RTK Query Docs. There's also information in the docs about how to handle pagination with tags.
Instructor: [0:00] Open up DogsPage.jsx and scroll down to the addDog section. Here, we use unwrapped to refetch every time we add in dog. There's actually a better way. Let's remove that code now, save the file, and go into apiSlice.js.
[0:15] Here, we're going to replace our keepUnusedDataFor timeout with something called tagTypes. We're going to declare two tagTypes -- services and dogs. Now, for each of our queries in mutations, we need to specify that they either provides tags or invalidate tags.
[0:31] Let's start with getDogs. We're going to say that getDogs provides tagsDogs, and we're going to say that addDog invalidates tagsDogs. Let's watch what happens.
[0:42] Open up the website, go to the MyDogs page. Let's add a new dog called Babe, a little bitty cocker spaniel. When I add a dog, the call to refetch the getDogsQuery happens automatically because of tags. Let me just show you again how easy that was.
[0:58] I set up the tagTypes. I then decided getDogs provides the dogs tag and addDogs invalidates the dogs tag. When we initially call getDogs, it will basically cache them with the key of dogs. When we add a dog, it says we should invalidate anything with that dog's key. Then it'll pull the data fresh.
[1:18] All the fancy stuff we did with manually piping through refetch, we don't actually need to do. We just have to declare these tags. There's a lot of really interesting things that you can do with tags and a link to that information in the description below.