Bertuz
Bertuz

Reputation: 2576

fetching a plain/text with redux-api-middleware

Can I fetch a txt file with redux-api-middleware? If yes, how? According to the doc the body is set to undefined if not application/JSON compliant, but what I will get is a simple text/plain

Upvotes: 1

Views: 2346

Answers (1)

Titenis
Titenis

Reputation: 825

Basically what I did was altering fetch action and doing my custom stuff with response data. Example:

fetch: async (...args) => {
    const response = await fetch(...args);

    if (response.ok && response.status === 200) {
      const reader = response.body.getReader();
      const type = response.headers.get('content-type');
      const filename = filenameExtractor(response.headers.get('content-disposition'));
      const { value } = await reader.read();

      fileSaver({ value, filename, type });
    }

    return response;
  },

This piece of code reads response contents and pushes them for download to the browser. filenameExtractor and fileSaver are custom functions. This way response is not altered.

Using such approach you can further modify response and create json yourself for data to be able to be saved in redux like:

const response = await fetch(...args);

return new Response(
    JSON.stringify({ data: response.body })
);

Upvotes: 1

Related Questions