this is my first time coding in Javascript/React JS so I'm not sure what is wrong here. getLicensees() send a GET request it my API and returns all the licensees. This works so far, also the console logs are working and printing the correct value.
constructor(props) {
super(props);
this.state = {licensees: []};
let licenseeResponse = LicensingService.getLicensees()
.then(licensees => {
this.state.licensees = licensees;
console.log("component", licensees);
console.log(licensees[0].city);
});
}
I'm trying to generate a table out of all the information’s inside my licensees object. But I can’t use this.state.licensees[0].city inside my render() method.
render() {
return (
<main id="content">
<div id="head">
<h4 className="headline">
Liste aller Lizenznehmer
</h4>
<div className="licenseeTable">
<table>
<tr>
<th>Lizenz nehmer</th>
<th>Aktuelles Zertifikat</th>
<th>Details</th>
</tr>
<tr>
<td>{this.state.licensees[0].city}</td>
<td>test2</td>
<td>test3</td>
</tr>
</table>
</div>
</div>
</main>
);
}
how can I do this properly?
--My solution:
componentDidMount() {
console.log('component did mount..', this);
LicensingService.getLicensees()
.then(licensees => {
this.setState({licensees});
console.log(licensees);
});
}
...
{
this.state.licensees.map(license => {
return <tr>
<td>{license.company}</td>
<td>{license.testCertificate.toString()}</td>
<td>{license.city}</td>
</tr>
})
}
this.setState({licensees}) is the correct way to assign value to the state object.
setStatemethod outside the constructor (for exmaple in thecomponentDidMounthook) when fetching some data (i assumegetLicenseesis some async code)this.setState({licensees});??