Reputation: 77
I am running Reactjs and mongdb. In Reactjs, once user selects the value, I am sending that into mongob
addTodo(event) {
event.preventDefault();
var roomID = this.state.selectedRoomID;
console.log(RoomID); //This value is printed correctly
const { mongodb } = this.props;
mongodb.db("attendance")
.collection("MasterDB").find({"RoomID": roomID}).asArray()
.then(MasterDB => {
this.setState({ MasterDB }); console.log("inside"+this.state.MasterDB.length);
});
console.log("outside"+this.state.MasterDB.length)
a)
Here first console.log is printing correctly.
b)
when ever I do find with roomID=1 explicitly the Query method is working.
whenever I keep roomID=this.state.selectedRoomID;.
Query is not working because roomID is not getting any value.
I am not sure why it is not getting that value.
c)
When I execute I see,
console.log(outside) is printed first and than
console.logg(inside) is printed.
As this is sequential, I am expecting the order other way. is there a way I can make sure first the lookup in mongodb happens first that is (console.log(inside) is printed first followed by console.log(outside)?
I see this as issue with reactjs the way I am sending the variables
Upvotes: 1
Views: 68
Reputation: 56
I need to look at the code when selectedRoomID is set to figure out why it is not getting any value.
As for the code to execute synchronously, either use Promises or Async/Await. That should help you run the code in the way you want it.
For example, in the code you posted, if you put the console log statement inside the then function, it should work fine. Or you can make the whole mongodb command a promise and wait for it to finish before proceeding further.
Upvotes: 4