rtk-upload-utils
v1.0.4
Published
A utility package for integrating file upload/download with progress tracking into your Redux Toolkit Query API slices.
Readme
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/toolkitreactreact-redux
Make sure you have these installed in your project.
Installation
npm install rtk-upload-utilsUsage
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 asfetchBaseQueryfrom 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
