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 });
}
}
asyncawaitcode 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.Syntax error: Can not use keyword 'await' outside an async function