how to get work Fetch API with Rails and React.
Setup: Rails 5, Sprockets and React from Webpacker.
What I'm trying to achieve here is use Fetch API to fetch and load data to ReactBootstrapTable API.
import React from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import 'whatwg-fetch'
class ExampleTable extends React.Component {
constructor() {
super();
this.state = {
datatable: [], // I'm not sure if I can use array to json data.
};
}
// I'm new to React, so I'm not sure if I'm passing props right
componentDidMount() {
console.log('start componentDidMount');
fetch('https://www.test.com/test.json')
.then(function(response) {
return response.json();
}).then(function(response) {
let datatable = response;
this.setStates({ datatable });
}).catch(function(ex) {
console.log('parsing failed', ex);
});
}
render() {
return (
<div>
<BootstrapTable
data={this.states.datatable} //Here, I'm passing data to the table
pagination
striped hover condensed
options={ { noDataText: 'Empty Table' } }>
<TableHeaderColumn isKey dataField='id' width='80px' dataAlign='center'>
ID
</TableHeaderColumn>
<TableHeaderColumn dataField='test'width='300px' dataAlign='left'>
Test
</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
}
export default ExampleTable;
The main problem here is that I'm not able to use Fetch API and also I'm not totally sure about the way I'm passing data to the table (basically how to use react)
I'm getting a error/warning from my IDE
fetch is not defined
And another error message from the Firefox console:
The above error occurred in the component: in ExampleTable
TypeError: this.states is undefined
I installed the Fetch API through yarn and checked the node_modules/whatwg-fetch folder. As described from the github API, I imported 'whatwg-fetch' as showed in the code above.
I don't know what else I should do. I installed ReactBoostrapTable in the same way and got succeeded doing it. Everything else is working fine.