reduxredux-toolkitreact-queryreselectrtk-query

How to get partial data from RTK query


I am started to use RTK query and I am not sure to use it properly when I need to get just one element of my cached data.

I have an object like this cached:

{
 id: "1",
 age: 18,
 name: "John"
}

And in one of my hook I use this following code:

const { data: { id } = {} } = useMyQuery();

So my question is how I can avoid a trigger of my hook if "name" or "age" change but not "id".

There is a way to create a memo selector on this cached data ?


UPDATE:

Here is the link of the documentation of selectFromResult: link

After some usage of selectFromResult it's appears we have to manage by ourself the memoization if the returned data.

It's in the documentation but lost in the limb. Here is the link.


Solution

  • You want to use selectFromResult:

    const { data: { id } = {} } = useMyQuery(undefined, {
      selectFromResult: ({isSuccess, data}) => ({ isSuccess, data: data.id }) 
    };
    

    Note that this also allows you to remove properties like isLoading, isSuccess etc which would also cause a potential rerender - this example only keeps isSuccess.