Home > database >  'firebase' is not defined error using React
'firebase' is not defined error using React

Time:04-28

I looked at the websites with this problem, but none of those apply to my situation. I don't know why 'firebase' is not defined. I don't know what's wrong with my code, I need someone to look at it. This error is taking place on line 42 of my code and I don't know why I'm getting this error. I tried accessing the firebase database by using the following code on line 42. React.js code:

import React, { useState } from 'react';
import { Button } from '@mui/material';
import { storage, db, serverTimeStamp } from "./firebase";

function ImageUpload({username}) {
  const [image, setImage] = useState(null); // it will be "choose file" option
  const [progress, setProgress] = useState(0);
  const [caption, setCaption] = useState(''); // caption will be empty by default, so that it will show placeholder 
  
  const handleChange = (e) => { //e.target.files[0] means select the first file that you selected
    if (e.target.files[0]) {
      setImage(e.target.files[0]); // set the image in state to that
    }
  };

  const handleUpload = () => {
    const uploadTask = storage.ref(`images/$(image.name)`).put(image); //storage.ref means get a reference, so access the storage in firebase get a reference to "images" folder were storing everything inside of it. And "image.name" is the file we selected. "put.image" is greabbing the image and putting in there. 
    uploadTask.on(
      "state_changed",
      (snapshot) => {
        //progress function ...
        const progress = Math.round(
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        ); // It's going to work out a number between 0 and 100 and it's going to give you a sort of exact progress indicator from 0 to 100  
        setProgress(progress);
      },
      (error) => {
        //error function ...
        console.log(error);
      },
      
      //what happens after the upload completes function
      () => {
        //complete function ...
        storage
          .ref("images") //Go to images folder
          .child(image.name) // Go to the image file, and
          .getDownloadUrl() // give me the download Url, once it's uploaded it gives us a "download url" 
          .then(url => {
            //post image in db
            db.collection("posts").add({
              timestamp: serverTimeStamp(), // our "timestamp" is based on the server where our code is living. It's going to help us sort the posts by the correct timings. We want all the recent ones at the top. It adjusts the time with where they are living, so they are consistent with one another. So if you are in la and someone is in london the post will show up at the same time no matter where they are.
              caption: caption, // stored the caption in some state, so we can do this
              imageUrl: url, // the imageUrl is literally going to be the "download Url" that we just got. We got the uploaded image, and use that as the image url. it's uploaded to firebase storage, and put it in the database. we are using this downloaded link as a part of our post.
              username: username, // we have it inside of App.js at the moment
            });

            setProgress(0); // set progress back to 0 after we reach 100 percent. 
            setCaption(""); // we want to reset the user forms
            setImage(null); // we want to reset the user forms

          }) // now we want to post the image to the database  
      }
    ) // "on state changed" give me a snapshot, it's an asynchronous process, it isn't immediate. We want to keep track of it, we want to know how long it is going to take. Give me snapshots of the progress.
  }

  return (
    <div>
      {/* I want to have... */}
      {/* Caption Input */}
      {/* File Picker */}
      {/* Post Button */}                                 
      <progress value={progress} max="100" />
      <input type="text" placeholder="Enter a caption..." onChange={event => setCaption(event.target.value)} /> {/* Every key press you do on the input field it's going to fire off an event, updating caption variable on the fly */}
      <input type="file" onChange={handleChange} />
      <Button onClick={handleUpload}>
        Upload
      </Button>
    </div>
  )
}

export default ImageUpload

Firebase.js code:

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/storage';
import "firebase/compat/storage";

const firebaseApp = firebase.initializeApp //
const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage().ref();
const serverTimeStamp = firebase.firestore.FieldValue.serverTimestamp;

export { db, auth, storage, serverTimeStamp };

export default db;

CodePudding user response:

You have not imported Firebase SDK in this file. Instead you can just export server timestamp from firebase.js itself as shown below:

const db = firebase.firestore();
// ..

const serverTimestamp = firebase.firestore.Fieldvalue.serverTimestamp;

export { db, serverTimestamp }

Then import it wherever required:

import { serverTimestamp, db } from "./firebase";

db.collection("posts").add({
  timestamp: serverTimestamp(),
  caption: caption,
  imageUrl: url,
  username: username, 
});
  • Related