I am new to react. I am trying to fetch data from remote server using _fetchUsers()
dynamically. The state apiUrl should be changed when clicking different nav tabs, although not showing here. The problems, I find that, the log before $.ajax
function shows empty string of this.state.apiurl
. If I hardcode the url on ajax's url property, the ajax can return right response. Can someone explain why I fail to setState for the apiurl, is the reason related to componentWillMount()
export default class RegiteredUserTable extends Component {
constructor() {
super();
this.state = {
registeredUsers:[],
tableProperties:[],
apiUrl:''
}
}
_fetchUsers() {
console.log("this.props", this.props);
if(this.props.match.params.tableId === "buyer-table"){
this.setState({apiUrl:'/buyers/list-buyers'});
} else if (this.props.match.params.tableId === "seller-table") {
this.setState({apiUrl:'/sellers/list-sellers/'});
}
console.log('this.state.apiUrl',this.state.apiUrl);
$.ajax({
method: 'GET',
url: `${this.state.apiUrl}`,
success: (res) => {
console.log('res',res);
let registeredUsers = res.data;
this.setState({registeredUsers});
}
});
}
_getTableProperty() {
//property array
console.log('this.state.registeredUsers',this.state.registeredUsers);
const tableProperties = this.state.registeredUsers[0].keys;
this.setState({tableProperties});
return tableProperties.map(tableProperty => {
return (
<th>{tableProperty}</th>
)
})
}
_getUsers() {
return this.state.registeredUsers.map(registeredUser => {
return (
<tr>
<td>{registeredUser.id}</td>
<td>{registeredUser.first_name}</td>
<td>{registeredUser.last_name}</td>
</tr>
);
}
)
}
componentWillMount() {
this._fetchUsers();
}
render() {
return(
<div className="container">
<div className="row">
<div className="col-xs-12">
<div className="table-responsive">
<table className="table table-bordered table-hover">
<caption className="text-center">Agents' data</caption>
<thead>
<tr>
{this._getTableProperty()}
</tr>
</thead>
<tbody>
{this._getUsers()}
</tbody>
<tfoot>
<tr>
<td colSpan="5" className="text-center">Data retrieved from <a href="http://www.infoplease.com/ipa/A0855611.html" target="_blank">infoplease</a> and <a href="http://www.worldometers.info/world-population/population-by-country/" target="_blank">worldometers</a>.</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
);
}
}