In this lesson we rely on useMemo
to to give additional properties to data returned from our query hook. This is not the recommended approach to modifying a server response. That would be the transformResponse
property shown in the next lesson, but I wanted to demonstrate how easy it was to combine typical react features like useMemo
with RTK Query results. This approach can work well if you need to modify data in a single component and no where else. It can also be combined with a custom hook that encapsulates both the query and the useMemo
call to be made more reusable. In the sample code I've provided an example of what that hook might look like.
Instructor: [0:00] Here on the DogsPage, you may notice that we're actually missing two very important things, the size and the age. Back when we were fetching this data using thunks, we used to manually calculate size and age based on the weight and date of birth properties that came back from our service.
[0:16] We're no longer making that adjustment. Let's correct that. In DogsPage.jsx, go ahead and import useMemo from React. Let's rename myDogs here to Dogs and then we'll say const myDogs=useMemo passing a function.
[0:34] For our second argument, the dependencies array will pass in our dogs object. Then, inside this function, let's go over to dogsSlice and let's copy over this for loop here. Const allDogs=empty object to there and we'll return allDogs at the end.
[0:52] Now getSize and getAge, I believe are exported from our dogsSlice. We can pull those in easily. Here we're using useMemo to modify the results that came back from our service and dogs, and add these two additional properties, size and age, every single time that dogs change.
[1:11] For the most part, this approach works best when you only need to make changes that show up in one place. Let's see what happens now back on our website. It looks like the size and age have returned.