I am trying to take a post that contains an image and upload it to firebase storage. Originally I had an error saying storage was not a function, but have change it to a new const as storageRef.
Now I am getting an error that .putString() isn't a function. I am passing in an image from my state variable and "data_url" as the 2nd arg. Why am I getting this error and is there anything else that seems to be off with my code?
Firebase.js
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getStorage, ref } from 'firebase/storage';
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const storage = getStorage();
File where Error is happening:
import React, { useRef, useState } from 'react';
import Image from 'next/image';
import { useSession } from 'next-auth/react';
import { db, storage } from '../firebase';
import { collection, serverTimestamp, addDoc } from 'firebase/firestore';
import { ref } from 'firebase/storage';
function InputBox() {
const { data: session } = useSession();
const [imageToPost, setImageToPost] = useState(null);
const inputRef = useRef(null);
const filePickerRef = useRef(null);
const sendPost = (e) => {
e.preventDefault();
if (!inputRef.current.value) return;
try {
const docRef = addDoc(collection(db, 'posts'), {
message: inputRef.current.value,
name: session.user.name,
email: session.user.email,
image: session.user.email,
timestamp: serverTimestamp(),
}).then((doc) => {
if (imageToPost) {
const storageRef = ref(storage, `posts/${doc.id}`);
const uploadTask = storageRef.putString(imageToPost, 'data_url');
removeImage();
uploadTask.on(
'state_change',
null,
(error) => console.error(error),
() => {
// When upload completes
storageRef
.ref(`posts`)
.child(doc.id)
.getDownloadURL()
.then((url) => {
docRef.addDoc(
Collection(db, 'posts')
.doc(doc.id)
.set(
{
postImage: url,
},
{ merge: true }
)
);
});
}
);
}
});
console.log(docRef.id);
} catch (e) {
console.log('ERROR ADDING DOC:', e);
}
Thanks in advance, Firebase is updating all the time and I still find this somewhat confusing.