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

207 Views Asked by At

How do I store an image with react-query firebase? Currently my code stores a chosen image locally but mutating it to Firestore just pushes the URI as string value:

import { useAuthUser } from "@react-query-firebase/auth";
import { useFirestoreCollectionMutation } from "@react-query-firebase/firestore";
import { collection } from "firebase/firestore";

const user = useAuthUser(["user"], auth);
const ref = collection(firestore, `/Users/${user.data?.uid}/Trips`);
const tripMutation = useFirestoreCollectionMutation(ref);

const [image, setImage] = useState<string|null>(null);

const saveTrip = () =>{
  tripMutation.mutate({
    name: trip.name,
   image: image //file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540glenncito%252Fapp/ImagePicker/130061bd-9b7b-4839-903d-d2b7e469384d.jpeg
  });
}
const pickImage = async () => {
  // No permissions request is necessary for launching the image library
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.All,
    allowsEditing: true,
    aspect: [5, 3],
    quality: 1,
  });

  console.log(result);

  if (!result.canceled) {
    setImage(result.assets[0].uri);
  }
};

As an alternative I know I could just encode and store it as base64, but is there not a better way?

1

There are 1 best solutions below

0
On

While it's possible to store binary data in Firestore, it'll get expensive quickly. I recommend instead using a dedicated file storage service for your images, such as Cloud Storage. Uploading files to Cloud Storage from client-side JavaScript code is documented here.