-2

There is something wrong with my error function when I look at my browser error and I don't why putting down a console.log with error would be a problem. I could use help figuring out this problem. It's on line 29 of my imageUpload.js. I don't know what this error is and I have never encountered it before. Here is my React 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" gives 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

Here is my firebase code:

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

const firebaseApp = firebase.initializeApp({ 
apiKey: "AIzaSyBl_kNHH8oIn17VrR2mcKQqOn3eAZo-Osw",
authDomain: "instagram-clone-react-82ab7.firebaseapp.com",
projectId: "instagram-clone-react-82ab7",
storageBucket: "instagram-clone-react-82ab7.appspot.com",
messagingSenderId: "562669348604",
appId: "1:562669348604:web:ae6a7cee3832803e761979",
measurementId: "G-6PENZ2M8LS"
});

const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
const serverTimeStamp = firebase.firestore.FieldValue.serverTimeStamp;

export { db, auth, storage, serverTimeStamp };

export default db;

Browser Error: enter image description here

Adam Breslin
  • 69
  • 2
  • 10
  • Please [edit] your question so that the **title** and content match your actual problem. Please also include the **minimal** amount of code required to understand and replicate the error. Please also provide error messages as text content, not images – Phil Apr 28 '22 at 00:38
  • FYI you're using the wrong delimiters in your ref template literal. It should be `storage.ref(\`images/${image.name}\`)` (note `${...}`, not `$(...)`). This question is just one long line of typos and should be closed – Phil Apr 28 '22 at 00:45
  • I recommend [reading documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) over watching coding videos. It's much easier to see specific syntax – Phil Apr 28 '22 at 00:49
  • @Phil Do you see anything wrong with my error function? – Adam Breslin Apr 28 '22 at 00:54
  • @Phil I already fixed that in my own code, and it is still giving me the same error in my screenshot. Did you not see the screenshot of the error message where it says there is a problem on line 28 where my error function is at? I even have it commented it out where it says error function. – Adam Breslin Apr 29 '22 at 05:21
  • It doesn't look any different in your question so how can anyone tell? – Phil Apr 29 '22 at 05:22

1 Answers1

1

Looks like you want to use this instead of "firebase/storage" so you can use the old v8 API instead of the new v9.

import 'firebase/compat/storage';

You are already using the compat wrappers for firestore and auth. Read the documentation to learn more.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441