0

I had referred to solutions such as Array data not rendering in data table using this.props - ReactJS

and TypeError: this.$el.DataTable is not a function( REACT.JS)

but I still have no idea why my table is not showing. And there will be error

this.$el.DataTable is not a function

if I comment if (!this.el) return; in componentDidMount.

This is my code, FetchData.js:

import React, { Component } from 'react';
import $ from 'jquery';
import DataTable from 'datatables.net';

$.DataTable = DataTable;

export class FetchData extends Component {
   static displayName = FetchData.name;

   constructor(props) {
      super(props);
      this.state = {
        forecasts: [],
        loading: true
     };
   }

 componentDidMount() {
    this.populateWeatherData();
    if (!this.el) return;
    this.$el = $(this.el);
    this.$el.DataTable({
        data: this.props.forecasts,
        column: [
            { title: "Date" },
            { title: "Temp. (C)" },
            { title: "Temp. (F)" },
            { title: "Summary" }
        ]
    })
}

static renderForecastsTable(forecasts) {
    return (
        <div>
            <table id="dtBasicExample" data={forecasts} className="table table-striped table-bordered table-sm" aria-labelledby="tabelLabel" cellSpacing="0" width="100%" ref={el => (this.el = el)}>
            </table>
        </div>
    );
}

render() {
    let contents = this.state.loading
        ? <p><em>Loading...</em></p>
        : FetchData.renderForecastsTable(this.state.forecasts);
   
    return (
        <div>
        <h1 id="tabelLabel" >Weather forecast</h1>
        <p>This component demonstrates fetching data from the server.</p>
        {contents}
        </div>
    );
}

async populateWeatherData() {
    const response = await fetch('weatherforecast');
    const data = await response.json();
    this.setState({ forecasts: data, loading: false });
}

}

3
  • try moving your async await code here --> async componentDidMount() { await this.populateWeatherData(); and see if it works. i cannot test it right now in order to post an answer, so I'm writing it as a comment first. Commented Jul 26, 2020 at 16:14
  • Hi @Apostolos, i tried to move as what you suggested, and remain the async in populateWeatherData as well, but the table still not showing. i got this error if i remove async from populateWeatherData: Syntax error: Can not use keyword 'await' outside an async function Commented Jul 27, 2020 at 1:03
  • is there a chance that you can put a codesandbox link in order to work on that and help you? Commented Jul 27, 2020 at 6:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.