A utility package for integrating file upload/download with progress tracking into your Redux Toolkit Query API slices.
This package requires the following peer dependencies:
@reduxjs/toolkit
react
react-redux
Make sure you have these installed in your project.
npm install rtk-upload-utils
import { getFetchBaseQuery } from 'rtk-upload-utils';
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,
}),
}),
}),
});
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>;
};
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
-
props
: The same arguments asfetchBaseQuery
from RTK Query.
-
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.
Contributions are welcome! Please submit a pull request.
MIT