Search code examples
reactjsexport-to-excel

Download excel file before query in fully completed


I am used library react-data-export.

My problem is that I created the excel file before finishing the query, now I have to press twice to make it work

Code:

import ReactExport from "react-data-export";
const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
import axios from 'axios';

class Main extends Component {
    constructor() {
        super();
        this.state = {
            multiDataSet: []
        }
        this.getDataExcel = this.getDataExcel.bind(this);
    }

getDataExcel() {
    let self = this;
    axios.get('/app/webapi/datos/excel'
        ).then(function (response) {
            self.setState({ multiDataSet: response.data});
        })
        .catch(function (error) {
            console.log(error);
        });
}   
render() {
    return (
        <ExcelFile name="excel2" filename="excelDatos" element={<Button label="Exportar" icon="fa fa-file-excel-o" onClick={this.getDataExcel}/>}>
            <ExcelSheet dataSet={this.state.multiDataSet} name="Datos_Excel"/>
        </ExcelFile>

    );
)

How to wait for the query to finish to create the excel?


Solution

  • You can start fetching the data on component mount (before the download button was clicked), and render the ExcelFile only after the data was fetched. Like so:

    class Main extends Component {
        constructor() {
            super();
            this.state = {
                fetching: true,
                multiDataSet: null,
            }
            this.getDataExcel = this.getDataExcel.bind(this);
        }
    
        componentDidMount() {
            // ********* the data is fetched on component mount, before the download button appears *********
            this.getDataExcel();
        }
    
        getDataExcel() {
            let self = this;
            axios.get('/app/webapi/datos/excel'
                ).then(function (response) {
                    self.setState({ multiDataSet: response.data, fetching: false });
                })
                .catch(function (error) {
                    console.log(error);
                    self.setState({ fetching: false });
                });
        }   
    
        render() {
            const { fetching, multiDataSet } = this.state;
            if (fetching) return <div>Loading...</div>;
            if (!multiDataSet) return <div>Failed to fetch data</div>;
    
            return (
                // ********* notice I removed the onClick event from the button *********
                <ExcelFile name="excel2" filename="excelDatos" element={<Button label="Exportar" icon="fa fa-file-excel-o"/>}>
                    <ExcelSheet dataSet={this.state.multiDataSet} name="Datos_Excel"/>
                </ExcelFile>
            );
        }
    }