Skip to content

Handle StreamingResponse and Server-Sent Events #3701

Open
@saschahofmann

Description

@saschahofmann

Use Case

I want to display a Progress bar for process running in the backend. I am also writing the API so I can make it anything: a streaming response, SSE or even a websocket. I managed to make rtk-query work with all three of these solutions but only for GET requests. In my case, the process is triggered by a POST request and I seem unable to make it work.

using onCacheEntryAdded

I would like to see rtk-query handling streaming responses and/or SSE. I made a simple version work with a StreamingResponse using the onCacheEntryAdded prop similar to how it's used in the docs for websockets. It feels quite quirky because, I have to set the original queryFn: () => ({data: null}) and then write the whole fetching logic inside the onCacheEntryAdded function.

      async onCacheEntryAdded(arg, { cacheDataLoaded }) {
        console.log('here', arg);
        await cacheDataLoaded;
        // Would be nice if I had access to the baseQuery here
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_URL}/risk_profiles/`
        );
        const reader = response.body
          .pipeThrough(new TextDecoderStream())
          .getReader();
        let done, value;
        while (!done) {
          ({ value, done } = await reader.read());
          // Overwrite the data value
          updateCachedData(() => value);
        }
      }

Without having looked at the code, I could imagine that maybe a returned ReadableStream response could be handled differently. Unfortunately, I can imagine two ways consecutive responses should be handled

a) By overwriting the previous value
b) By appending to a list

I'd say b) is the more general case and could be the default.

In any case, above works for a get request. Unfortunately, the isLoading is already false after it ran the queryFn and I haven't found a way to change it back to true.

The bigger issue is that this doesn't work for mutations like POST requests. While the mutation builder has onCacheEntryAdded property, it has no access to updateCachedData. Is there any specific reason for this? I think adding that to the props would be enough for me to hack a solution together for my use case. Even now I might be able to use the dispatch function, but I would love to see an easier way to do this in rtk-query.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions