React Firebase storage getDownloadUrl to a link

Viewed 1385

I'm trying to make a download link to get a CSV file from my Firebase Storage. In the Class you can see we are using a function to put de download URL in de link.

import React, { Component } from 'react'
import { storage, auth }  from '../../handlers/Firebase'
import { Link } from 'react-router-dom';

class Dashboard extends Component {

    constructor() {
        super();
        this.state = {
            userAuth : auth.currentUser
        }
        this.getDownloadUrl = this.getDownloadUrl.bind(this);
    }

    getDownloadUrl(){
        var storageRef = storage.ref('images/test.csv');
        storageRef.getDownloadURL().then(function(url) {
            // we get correct URL in the console, but when we click on the 'a' the page just refresh...
            console.log( "Got download url: ", url );
            var link_item = document.getElementById('download-link')
            link_item.setAttribute('href', url)
        });
    }

    render() {

        //This is the data for in the CSV file
        var csvData = 'Title 1;Title 2;Title 3\r\nTest 1;Test 2;Test 3';

        var file = new Blob([csvData], {
            encoding: "UTF-8",
            type: "text/csv;charset=UTF-8"
        });

        // Create a root reference
        var storageRef = storage.ref();

        // Create a reference to 'images/mountains.jpg'
        var Ref = storageRef.child('images/test.csv');

        Ref.put(file).then(function(snapshot) {
            console.log('Uploaded a blob or file!');
        });

        return (
            <div className="dashboard-page">
                <div className="container">
                    <h2>Dashboard</h2>
                    <Link to={this.getDownloadUrl} id="download-link">Download file</Link>
                </div>
            </div>
        )

    }

}

export default Dashboard

I get the URL of the file in the link. But when i click on the link the page just refresh and nothing is downloaded. What am I doing wrong?

1 Answers

I Fixed it. I putted the function getDownloadUrl in the render() of the class. I still don't understand why i cannot just put a return on the function to load the URL in de link. But maybe someone can tell me that!

Related