2

I have 2 endpoints. One for fetching a list of users (with all related data), and one for just fetching one of them. I would like to be able to share cached data between these 2 endpoints.

I need this because I have 2 pages, one with the list of users, and one that displays the data of a given user where I would like to be able to reuse the data that's already in the list, or in case it's not there, just fetch the data I need.

Here are the two endpoints:

getTeachers: builder.query({
      query: ({ page, orderBy, orderDirection }) =>
        buildQueryWithParams('teachers', {
          limit: bigPaginationLimit,
          offset: (page - 1) * bigPaginationLimit,
          orderBy,
          orderDirection
        }),
      providesTags: (res) =>
        res.list
          ? [
              res.list.map((item) => ({
                type: 'teacher',
                id: item.id
              }))
            ]
          : [{ type: 'teacher', id: 'list' }]
getTeacher: builder.query({
      query: (id) => `/teachers/${id}`,
      providesTags: (res, error, id) => [{ type: 'teacher', id }]
    })

I was hoping that giving the objects the same tags would make it so that they share a cache, but I've since found out that RTK Query doesn't use the tags for the cache.

Is there any way of sharing caches between these two endpoints?
If not, how could I go about using the data from the list if it's there, and otherwise just fetching the single user.

1 Answer 1

0
  1. Perform a check on the data returned from getTeachers for the given user's existence using some array function(Like filter orfind). This step assumes you know the list of given user's you would be checking for.
  2. If it exists then send a query function prop as null to the child component that would be using that id's data and use the filtered data for that user returned from getTeachers as source.
  3. if not send the getTeacher as a prop along with userId, the query function which would run when the child component loads.

Here is an example of same component running different queries based on two different scenarios: https://github.com/marciamoss/1stop_rtk/blob/main/src/components/MusicPage/MusicPage.js calls a child component <MusicList> with two different query functions (line 41 and line 85). In your case you just make the query function null for one of the scenario and initialize data to getTeachers filtered data for that user.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunate that this has to be done manually, it seems like a simple use case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.