乐闻世界logo
搜索文章和话题

How can I upload a file using " react - query " and " type - script "?

1个答案

1

Before uploading files with React Query, create a function to handle the actual upload logic. This typically involves using the fetch API or other libraries (such as axios) to send a POST request to the server.

Here is a TypeScript example function using fetch and FormData:

typescript
interface UploadResponse { success: boolean; message: string; url?: string; } async function uploadFile(file: File): Promise<UploadResponse> { const formData = new FormData(); formData.append("file", file); const response = await fetch("https://your-upload-endpoint.com", { method: "POST", body: formData, }); if (!response.ok) { throw new Error('Failed to upload file'); } return response.json(); }

Step 2: Using the useMutation Hook from React Query

The useMutation hook from React Query is ideal for handling asynchronous operations that may change server state, such as file uploads. By using useMutation, you can easily track upload status, handle errors, and update data.

In the component, you can use this hook and the upload function as follows:

typescript
import { useMutation } from 'react-query'; const FileUploader: React.FC = () => { const { mutate, isLoading, isError, error, isSuccess } = useMutation(uploadFile); const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => { if (event.target.files?.length) { const file = event.target.files[0]; mutate(file); // Invoke the upload function } }; return ( <div> <input type="file" onChange={handleFileChange} /> {isLoading && <p>Uploading...</p>} {isError && <p>Error: {error instanceof Error ? error.message : 'Unknown error'}</p>} {isSuccess && <p>Upload successful!</p>} </div> ); };

Step 3: Providing Feedback on Upload Status

As shown in the code above, you can inform users about the upload status in real time using flags like isLoading, isError, error, and isSuccess. This enhances user experience by keeping users informed about the current progress.

Summary

By combining the useMutation hook from react-query with TypeScript, you can create a robust and type-safe file upload feature. This approach simplifies state management and error handling while making the code clearer and easier to maintain.

2024年8月5日 11:32 回复

你的答案