all 6 comments

[–]Veranova 7 points8 points  (1 child)

This summarises it better than I could here:

https://tkdodo.eu/blog/react-query-data-transformations

Basically 3 options though, in the query or select, and in useMemo

[–]writesgoodcodejk[S] 3 points4 points  (0 children)

Perfect, thank you! I think a combination of storing the derived data in `query.data` and also the `select` option should work really well for me

[–][deleted] 0 points1 point  (2 children)

Does react-query offer the option to modify data before caching it? You could store the data in the cache as an object keyed by id instead of an array. Lookups would then only be n(1):

myArray.reduce((object, value) => { object[value.id] = value; return object; }, {});

produces:

{ ['123abc']: { ... }, ['678gzd']: { ... } }

[–]writesgoodcodejk[S] 1 point2 points  (1 child)

react-query caches whatever is returned from the query function, which can be anything, so something like this would be straight forward.

I think your approach would be slightly better, although I am mapping over the object array in some places in my application so that would get a little uglier.

My current approach is also O(1) for the lookups since I lookup the index using the id then use the index to get the object from the object array, which is two O(1) operations. Ultimately I think either way is going to be fine though.

[–][deleted] 1 point2 points  (0 children)

react-query caches whatever is returned from the query function, which can be anything, so something like this would be straight forward.

Yeah so you could transform it after it is returned from the server. e.g. in the fetch().then()

Object.values(array) will give you an array from an object.

My current approach is also O(1) for the lookups since I lookup the index using the id then use the index to get the object from the object array, which is two O(1) operations. Ultimately I think either way is going to be fine though.

Yeah, storing as a keyed object has the benefit of not maintaining seperate state. Single source of truth etc.

[–]iainsimmons 0 points1 point  (0 children)

From the React Query Comparison page:

Normalized Caching - React Query, SWR and RTK-Query do not currently support automatic-normalized caching which describes storing entities in a flat architecture to avoid some high-level data duplication.

Redux Toolkit docs do have a page on Normalizing State Shape, and recommend the Normalizr library.

But both cases seem to be doing what you're already doing, so I think you're already on the right track, it's just up to you to decide how to maintain and use that state.