Acquire the URL of an uploaded file stored in Firebase using Vue.js

I am encountering a small issue with my script. I am attempting to upload a file to Firebase storage using Vue.js. Everything seems to be working fine, except that the URL is null. My script deals with a form for book values which includes fields such as an id, title, description, price, pdf (the file), pdf_url, and the uploaded value of the script.

import firebase from "firebase";
import db from "./firebaseInit";
export default {
  name: "vendre",
  data : ()=> {
    return {
      id_livre: null,
      titre: null,
      description: null,
      prix_d : null,
      pdf : null,
      pdf_url : null,
      uploadValue : null
    }
  },
  methods: {

    onfileSelected(event){
      this.pdf_url = null;
      this.pdf = event.target.files[0]
      console.log(event);
    },

    saveBook(){
      this.pdf_url = null;
      const storageRef = firebase.storage().ref(`${this.pdf.name}`).put(this.pdf);
      storageRef.on(`state_changed`, snapshot=> {
          this.uploadValue = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      }, error => {console.log(error.message)}, () => { 
          this.uploadValue = 100;
          storageRef.snapshot.ref.getDownloadURL().then((url)=> {
            this.pdf_url = url;
          })
      })
      console.log(this.pdf_url);

      db.collection('Livres').add({
        id_livre : this.id_livre,
        titre : this.titre,
        description : this.description,
        url: this.pdf_url  
      }).then(docRef => { 
          this.$router.push('/');
          console.log(docRef);
      }).catch(error => console.log(error.message))
    }
  }
};

Answer №1

Retrieving the download link for a file requires making an asynchronous request to the server. As a result, any code that relies on the download URL should be placed within the callback function triggered upon successfully fetching the URL.

Here's an example:

saveBook(){
  this.pdf_url = null;
  const storageRef = firebase.storage().ref(`${this.pdf.name}`).put(this.pdf);
  storageRef.on(`state_changed`,snapshot=>{
      this.uploadValue = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
  }, error=>{console.log(error.message)}, ()=>{this.uploadValue =100;
    storageRef.snapshot.ref.getDownloadURL().then((url)=>{
      db.collection('Livres').add({
        id_livre : this.id_livre,
        titre : this.titre,
        description : this.description,
        url: url  
      }).then(docRef =>{ this.$router.push('/');console.log(docRef)
      }).catch(error =>console.log(error.message))
    })
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to apply a Redux filter to data while still preserving the existing state?

I've encountered some issues while working on a search feature using Redux. Here are the actions related to the search functionality: export const passengersDataAction = passengersData => ({ type: ActionTypes.PASSENGERS_DATA, // This is the a ...

"Nested AngularJS controllers: a deep dive into the world

Recently, I've been delving into the world of AngularJS and I can't shake the feeling that my approach to the paradigm might be a bit off. I have a controller for managing panes (linked to an ng-repeat) which tracks which panes the user has open ...

Could I potentially receive a null value in the event that I am provided with an empty array?

In my Typescript code, I am dealing with two arrays of objects. I need to find matches between the items in the first array and the second array. However, when there is no match, it returns an empty array: Here is the first array: let info = [ { &qu ...

How can user input be converted into a JavaScript variable?

Looking for help with my webpage - I want users to input their name and age. After hitting submit, I'd like the first input to be stored in a variable called 'name', and the second input in a variable called 'age'. Is this doable? ...

JavaScript vs. markup: deciding between generating an extensive list of options or including them directly in

Recently, I encountered an issue with a .NET page that included a large number of identical dropdown lists within a repeater. Unfortunately, the rendering performance of the website was below expectations. In an attempt to improve the performance, I exper ...

An error has occurred in the callback function for the watcher "function () { return this._data.$$state }": "Error: [vuex] It is forbidden to modify the vuex store state outside of a mutation"

Here is a screenshot of the error I encountered in the console This is the method that I am using The issue seems to be happening in mounted I have also included MapState in the Computed section While my code is currently functional, I am puzzled by th ...

Is it possible for jQuery to create a popup window displaying a specific value?

Using JavaScript, I have implemented functionality to open a child window when the user clicks on a button from the parent window. The child window contains a textbox and a button. When the user clicks on the button in the child window, I want to retrieve ...

Using jQuery to select a dictionary value as the default in an HTML dropdown list

I am looking to address a challenging issue with an HTML drop down menu. The data source for this menu is a dictionary, and I need the selected value's key to be stored in a hidden field. When the page reloads, I want to ensure that the value in the d ...

An empty response was received after making an Ajax request

Attempting to create an Ajax request and parse the response header to extract the "Location" attribute. Here is the code in question : let request = new XMLHttpRequest(); request.onreadystatechange = function() { if(request.readyState == 4 && ...

Sending an array object from Ajax to Django Framework

AJAX Script Explanation: Let's consider the variable arry1D contains values [0,1,2,3,4] $.ajax({ url: "{% url 'form_post' %}", type: "POST", data: { arry1D: arry1D, 'csrfmiddlewaretoken': tk }, ...

jQuery did not display the alert message

A JQuery weather plugin has been successfully implemented, but there is an issue with some code not displaying the data. The problem lies in the last section of the JQuery code, where a message should be displayed to the user when the temperature exceeds a ...

Learn how to effectively utilize DataBinder.Eval of repeater in ASP.NET button's OnClientClick JavaScript function

I am facing an issue with my asp.net webform repeater. Within the "ItemTemplate" of the repeater, I have added an asp:button and implemented the following code in the "OnClientClick" event of the button. // Here is a JavaScript function function Confirm ...

Is it possible to dynamically create new input fields by starting their index from the highest number after deletion?

I am working on a feature where users can add new rows with unique IDs and names. Everything works well, but the issue arises when deleting a row other than the last one. Here is an example of my code: $("#add_row").on('click', addRow); funct ...

Utilizing Vue Composition API for Implementing Global State Management among Components

Recently, I attempted to utilize the Vue Composition API for global state management. For instance, I created a file named useLoading.js to handle loading flags. useLoading.js import { reactive, toRefs } from '@vue/composition-api' export defau ...

The `await` keyword can only be used within an `async` function in

I attempted to create a music bot for my server, but it seems like I made a mistake. I followed instructions from this video, however, an error stating await is only valid in async function keeps popping up. module.exports = (msg) => { const ytdl ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

The function cannot be invoked. The 'Boolean' type does not have any call signatures. An error has occurred in the computed property of Vue3

Currently, I am working on creating a computed property that checks if an item is in the array. The function I have created returns a boolean value and takes one parameter, which is the item to be checked. isSelected: function (item: MediaGalleryItemTypes) ...

When using Mongoose's "find" function, it may sometimes return an empty result set

I am currently on a mission to locate all blogs created by a user with their userId. Below is the mongoose model I have for the blogs: var mongoose = require('mongoose'); var BlogSchema = new mongoose.Schema({ title:{ type: String, ...

What is the most effective way to send a Json array of objects from a child class component to its parent class component in a React application

Within the component Trivia, I have a state variable called currentQuestion that serves as an index. I've also created another class component called Questions which reads from a JSON file, and I want to pass it to Trivia like this: ... questions = & ...

Evaluating substrings within a separate string using JavaScript

I need to compare two strings to see if one is a substring of the other. Below are the code snippets: var string1 = "www.google.com , www.yahoo.com , www.msn.com, in.news.yahoo.com"; var string2 = "in.news.yahoo.com/huffington-post-removes-sonia-gandh ...