I'm new to Next.js. Im following a youtube tutorial to build facebook using - next.js, nexauth and firebase as database. I did npm install firebase, created a firebase.js file.
firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import "firebase/storage";
import firebase from "firebase";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "<mykey>",
authDomain: "<domain>",
projectId: "<projectId>",
storageBucket: "<storageBucket>",
messagingSenderId: "<messagingSenderId>",
appId: "<appId>"
};
if(!firebase.apps.length){
firebase.initializeApp(firebaseConfig)
}
// Initialize Firebase
const db = app.firestore();
const storage = firebase.storage();
export { db, storage };
In the inputbox.js where the user can write posts. On submitting the post, it will create a new collection named posts in the database and add the information by the user. But after pressing enter the page says
TypeError: Cannot read properties of undefined (reading 'collection')
I've imported everything required for this.
InputBox.js
import Image from "next/image";
import { useSession } from "next-auth/client";
import { EmojiHappyIcon } from "@heroicons/react/outline";
import { CameraIcon, VideoCameraIcon } from "@heroicons/react/solid";
import { useRef } from "react";
//imports for db
import { db } from "../firebase";
import firebase from "../firebase";
function InputBox(){
const [session] = useSession();
const inputRef = useRef(null);
const sendPost = (e) => {
e.preventDefault();
if(!inputRef.current.value) return;
//error
db.collection('posts').add({
message: inputRef.current.value,
name: session.user.name,
image: session.user.image,
email: session.user.email,
// timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
};
return (
<div className="bg-white rounded-2xl p-2 shadow-md text-gray-500 font-medium mt-6">
<div className="flex space-x-4 p-4 items-center">
<Image
className="rounded-full"
src={session.user.image}
width={40}
height={40}
layout="fixed"
/>
{/* Inputbox */}
<form className="flex flex-1">
<input
className="rounded-full h-12 bg-gray-100 flex-grow px-5 focus:outline-none"
type="text"
placeholder={`What's on your mind, ${session.user.name}`}
ref={inputRef}
></input>
<button hidden onClick={sendPost} type="submit" >Post</button>
</form>
</div>
</div>
);
}
export default InputBox;