rtk-incubator / rtk-query

Data fetching and caching addon for Redux Toolkit
https://redux-toolkit.js.org/rtk-query/overview
MIT License
626 stars 31 forks source link

"cache entry level" lifecycle #215

Closed phryneas closed 3 years ago

phryneas commented 3 years ago

We could introduce a cacheEntryContext next to the existing requestContext (renamed from just context and add two new lifecycle callbacks: cacheEntryAdded and cacheEntryCleared. Those two lifecycles would allow supporting stuff like graphql subscriptions or websocket streams.

    getPosts: build.query({
      query: (arg) => ({ url: `posts` }), // fetches data that will then be updated by a subscription
      cacheEntryAdded(arg, { dispatch, cacheEntryContext }) {
        cacheEntryContext.stopListening = ws.listen(() => {
          // ... 
          dispatch(
            api.util.updateQueryResult('cacheEntryAdded', arg, (draft) => {
              draft.foo = ...
            })
          )
        })
      },
      cacheEntryCleared({ id }, { dispatch, cacheEntryContext }) {
        cacheEntryContext.stopListening()
      },
    }),

OR we go useEffect here and have cacheEntryAdded just return a cleanup callback. Then we could skip all the cacheEntryContext nonsense and omit cacheEntryCleared

    getPosts: build.query({
      query: (arg) => ({ url: `posts` }), // fetches data that will then be updated by a subscription
      cacheEntryAdded(arg, { dispatch }) {
        const stopListening = ws.listen(() => {
          // ... 
          dispatch(
            api.util.updateQueryResult('cacheEntryAdded', arg, (draft) => {
              draft.foo = ...
            })
          )
        })
        return () => {
          stopListening()
        }
      }
    }),
markerikson commented 3 years ago

Lenz just put up a commit with hypothetical designs for three different variations on this concept: "context"-based, "callback"-based, and "promise"-based:

https://github.com/rtk-incubator/rtk-query/pull/223/files#diff-c3ac4236290f8a1c76845f190db173acaed90fec487886e4b0e90ecbf21f13b4

Thoughts?

phryneas commented 3 years ago

This is on the integration branch right now, closing it here.