1. 12
    Transforming RTK Query Data before Caching with transformResponse
    1m 13s

Transforming RTK Query Data before Caching with transformResponse

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet

We're currently modifying the data we get from RTK Query at the component level with useMemo. This works great when you have a single component that needs to have access to the data in a unique way. However, when you need to access that modified data in multiple components, it's better to use transformResponse.

Using transformResponse moves the data transformation into your cache, so any component subscribed to a given query will receive data in the updated format.

Instructor: [0:00] We're currently modifying the response from our dogs query and useMemo hook that stores the changes on a component by component basis. This is great for displaying the dogs on this page, but on our services page, we also need to access to those properties.

[0:15] First, we're going to delete this useMemo logic and return this to saying my dogs, get rid of the other changes in here. Then we'll open up apiSlice.js. Below our getDogs query, we're going to add a new key called transformResponse.

[0:31] This is going to take the object returned from the service. In this case, it's just dogs and it will allow us to return a new object that will get stored in our cache. In this case, I'm going to paste in the logic from our useMemo. Delete the useMemo rapper, save that.

[0:48] Looks like that should pretty much work, but we need to getSize and getAge helper functions. At this point, I'm not going to need them anywhere else. I'm just going to copy them right into the bottom of apiSlice.

[0:58] Now if I go back into the Dogs page, you can see the size and age are working properly. Over here in Services, size and age continue to work as I'm applying the filters needed to display the correct services.