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

How to store an image with react- query - firebase ?

1个答案

1

When using react-query with Firebase to store images, first ensure that Firebase Storage is set up and that the react-query and firebase libraries are installed and configured in your project.

Step 1: Setting Up Firebase

  1. Create a new project in the Firebase Console.
  2. Enable Firebase Storage.
  3. Install the Firebase SDK and configure it in your project.
bash
npm install firebase

Create a firebaseConfig.js file in your project:

javascript
import { initializeApp } from "firebase/app"; import { getStorage } from "firebase/storage"; const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_MESSAGING_SENDER_ID", appId: "YOUR_APP_ID" }; const app = initializeApp(firebaseConfig); export const storage = getStorage(app);

Step 2: Using react-query and Firebase Storage to Upload Images

  1. Install react-query:
bash
npm install react-query
  1. Create a custom hook for uploading images using react-query's useMutation. This hook handles the logic for uploading images.
javascript
import { useMutation } from 'react-query'; import { ref, uploadBytes } from 'firebase/storage'; import { storage } from './firebaseConfig'; // Import Firebase configuration const useUploadImage = () => { return useMutation(async (file) => { // Create a reference in Firebase Storage const storageRef = ref(storage, `images/${file.name}`); // Upload the file to the specified reference const snapshot = await uploadBytes(storageRef, file); return snapshot; }); };

Step 3: Using the Custom Hook in a Component

In a React component, use the useUploadImage hook to upload images.

javascript
import React, { useState } from 'react'; import { useUploadImage } from './hooks/useUploadImage'; // Import the created hook function ImageUploadComponent() { const [file, setFile] = useState(null); const { mutate: uploadImage, isLoading, error } = useUploadImage(); const handleFileChange = (event) => { setFile(event.target.files[0]); }; const handleUpload = () => { uploadImage(file); }; return ( <div> <input type="file" onChange={handleFileChange} /> {isLoading ? ( <p>Uploading...</p> ) : ( <button onClick={handleUpload}>Upload Image</button> )} {error && <p>Upload error: {error.message}</p>} </div> ); } export default ImageUploadComponent;

Summary

The steps above demonstrate how to combine react-query with Firebase Storage to upload images. This approach effectively manages image upload states, such as loading and error handling, while keeping components concise and maintainable.

2024年6月29日 12:07 回复

你的答案