How to handle streams on top of RTK Query?

78 Views Asked by At

I need to handle node streams using the RTK Query endpoints. The problem is that the official doc only includes the example for sockets, but that scenario doesn't work for Streams. Here is the endpoint definition:

...

teamSkillsActionableInsights: builder.mutation<Response, TeamSkillsReport>({
      query: (teamSkillsReportData) => ({
        url: "reports/team/skills/actionable-insights",
        method: "POST",
        body: teamSkillsReportData,
        responseHandler: async (response) => response.body,
      }),

...

And this is the consumption:

...

const [aiActionableInsights, setAiActionableInsights] = useState("");
const [updatePost] = useTeamSkillsActionableInsightsMutation();

...

const getUserSkillsActionableInsights = async () => {
    const response = await updatePost(teamSkillsReportData).unwrap();

    // Using While Loop
    let total = "";
    const reader = response?.getReader();
    const decoder = new TextDecoder("utf-8");
    while (true) {
      const { done, value: chunk } = await reader.read();
      if (done) break;

      const decodedValue = decoder.decode(chunk);
      total += decodedValue;
      setAiActionableInsights(total);
    }
  };

The server streams plain text with text/plain; charset=utf-8 header.

0

There are 0 best solutions below