I'm trying to fetching my data from mongo to the client-side to react. I succeed to set the state of the component to the correct fields from the endpoint API of my DB. But when I want to print my state to see if it is working the console print my an empty object although the state change and I see it in the console.[enter image description here][1]
getDataFromDb = () => {
const req = new Request('http://localhost:5000/family',{
method: 'GET',
cache: 'default'
});
fetch(req).then(res=>{
return res.json();
}).then(data=>{
console.log(data);
this.setState({
rooms: data
});
console.log(this.state.rooms);
}).
catch(err=>{
console("Error: " + err);
});
};
componentDidMount() {
this.getDataFromDb().then(result => this.setState({rooms: result}));
//let rooms = this.formatData(this.getDataFromDb());
//let featuredRooms = ...rooms.filter(room => room.featured===true);
//let maxPrice = Math.max(...rooms.map(item=>item.price));
//let maxSize = Math.max(...rooms.map(item=>item.size));
//new code:
let featuredRooms = this.state.rooms.filter(room=>room.featured===true);
let maxPrice = Math.max(this.state.rooms.map(item => item.price));
let maxSize = Math.max(this.state.rooms.map(item=> item.size));
this.setState({
// old code ---> rooms,
//rooms,
featuredRooms,
sortRooms: this.state.rooms,
//old code
//sortedRooms:rooms,
loading:false,
price:maxPrice,
maxPrice,
maxSize
});
this.printData();
}