rtk-upload-utils
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

RTK Upload Utils

A utility package for integrating file upload/download with progress tracking into your Redux Toolkit Query API slices.

Prerequisites

This package requires the following peer dependencies:

  • @reduxjs/toolkit
  • react
  • react-redux

Make sure you have these installed in your project.

Installation

npm install rtk-upload-utils

Usage

1. Import getFetchBaseQuery

import { getFetchBaseQuery } from 'rtk-upload-utils';

2. Configure your API Slice

Use getFetchBaseQuery as the baseQuery in your RTK Query API slice:

import { createApi } from '@reduxjs/toolkit/query/react';
import { getFetchBaseQuery } from 'rtk-upload-utils';

export const api = createApi({
  baseQuery: getFetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (builder) => ({
    uploadFile: builder.mutation<any, { file: File; onProgress?: (progress: number) => void }>({
      query: ({ file, onProgress }) => ({
        url: '/upload',
        method: 'POST',
        body: file,
        progress: true,
        onProgress,
      }),
    }),
    downloadFile: builder.mutation<any, { fileName: string }>({
      query: ({ fileName }) => ({
        url: `/download/${fileName}`,
        method: 'GET',
        isDownload: true,
      }),
    }),
  }),
});

3. Use in Your Component

const MyComponent = () => {
  const [uploadFile] = api.useUploadFileMutation();

  const handleUpload = async (file: File) => {
    await uploadFile({
      file,
      onProgress: (progress) => {
        console.log(`Upload progress: ${progress}%`);
      },
    });
  };

  return <button onClick={() => handleUpload(selectedFile)}>Upload</button>;
};

API Reference

getFetchBaseQuery(props: FetchBaseQueryArgs)

Returns a base query function for RTK Query, supporting:

  • Authentication headers (using a token from your auth state, if provided)
  • Progress tracking for uploads
  • File download support

Arguments

  • props: The same arguments as fetchBaseQuery from RTK Query.

The returned base query function accepts:

  • url: The URL to fetch.
  • method: The HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE').
  • body: The request body (for POST, PUT, etc.).
  • headers: An object containing custom headers.
  • progress: Boolean to enable upload progress tracking.
  • onProgress: Callback function called with the upload progress (0-100).
  • isDownload: Boolean to enable file download handling.

Contributing

Contributions are welcome! Please submit a pull request.

License

MIT

Dependents (0)

Package Sidebar

Install

npm i rtk-upload-utils

Weekly Downloads

248

Version

1.0.4

License

ISC

Unpacked Size

41.5 kB

Total Files

14

Last publish

Collaborators

  • miladhamzelou