Fetch is successful in below code (I have confirmed by looking at console - Network in browser) but the setState is not updating the allWeights array in state with the array of documents from MongoDB returned by API. When I use console.log() it prints what api returns but just setState is not working. I understand when render() executes allWeights array will have no value however after componentDidMount executes allWeights must have value if setState behaves as expected. I have searched for solutions provided for similar issue but they are not helpful for my issue. As the setState is not working the map function in render() throws error. Kindly help. I am stuck with this for last 3 days.
import React, {Component} from "react";
//
class TeamWeightsMain extends Component {
constructor(props) {
super(props);
this.state = {
allWeights: []
}
}
//
componentDidMount() {
console.log(`Entered componentDidMount()`);
fetch("http://localhost:8080/getallemployees")
.then(response => response.json())
.then((data) => {
this.setState(
{allWeights : data}
);
});
}
//
render() {
console.log(`Entered render() - allWeights value now : ${this.state.allWeights.toString() }`);
if(this.state.allWeights !== undefined && this.state.allWeights.length > 0) {
console.log(`this.state.allWeights.length: ${this.state.allWeights.length}`);
console.log(`this.state.allWeights: ${this.state.allWeights}`);
console.log(`this.state: ${this.state}`);
return(
<main>{
this.state.allWeights.map((emp,i) => {
return <div key={i}>
{emp.empName}
{emp.employeeWeights.map((weight,j) => {
return <div key={j} className="indentWeight">
Date: {new Date(weight.weighedOn).toLocaleDateString()}
{' '}
Weight: {weight.empWeight}
</div>
})}
</div>}
)
}
</main>)
}
else {
console.log(`Inside Not authorized : ${this.state.allWeights}`);
return (
<main>
<h2>Teamweights</h2>
<div className="indentWeights">
Sample text
</div>
</main>
)
}
}
}
//
export default TeamWeightsMain;