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
Published 2 years ago
Updated 2 years ago

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.

egghead
egghead
~ 22 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today