0

In RTKQ-documentation example cacheKey is undefined, but usually that is not the case. My current solution is to save cacheKey in a slice which makes it available both to selectFromResult and onQueryStarted (essentially everywhere) but I feel it is less than perfect. Is there some recommended way of storing and reusing cacheKey in RTKQ?

radulle
  • 1,437
  • 13
  • 19
  • In `selectFromResult` you essentially pass it into the query on the same statement, so it should be directly available for you? As for `onQueryStarted`, what do you want to use it for? Generally you should only need the arguments, if at all, but never the cache key itself (which is a string)? – phry Oct 14 '21 at 08:56
  • @phry if I pass only `id` to list items as it is recommended than list item has to know also the `cacheKey` which I can pass from parent so that I could use `selectFromResult`. In `onQueryStarted` I need it for optimistic/pessimistic updates so that I could know which cache to update. – radulle Oct 14 '21 at 10:13

1 Answers1

0

I think you might be using wrong terms here. cacheKey is an internal string representation of your argument and you will never interact with that string in RTK-Query.

You will need the same argument in some cases.

In onQueryStarted of a query, you might just be able updateCachedData from the lifecylce api, so you do not need the argument.

For selectFromResult, you will need to pass the same argument into the hook as you did elsewhere. In that case, you can either pass it down to a child using props or share it using Redux state.

phry
  • 35,762
  • 5
  • 67
  • 81
  • But isn't `updateCachedData` available for query endpoints only and optimistic/pessimistic updates are performed in mutation? – radulle Oct 14 '21 at 11:25
  • 1
    Sorry, I read over that part of your answer above. In that case, yes, sharing that query argument in some global way like an external slice is the way to go. – phry Oct 14 '21 at 11:35