Reputation: 11
I'm using the firstore, and I get information from the first.
Here, I want to retrieve data from the firstore and print it out, but there is a problem with asynchronous mode.
The output is output after undefined.
I want to know how to print it correctly.
When data is received, the function receives data, and the method of receiving data after searching the firestore.
in react component
index = (date) =>{
let date_total = UserAction.getIndex(date)
return date_total
}
render(){
const {user_list} = this.props;
console.log(this.state)
const date = "2020-02-24"
console.log("data",date)
let index = this.index(date) < this
console.log("index", index)
return(...)
and useraction function
export function getIndex(data){
let time_now = moment(data).utc().format()
const user_history_start = moment(time_now).startOf("d").utc().format();
const user_history_end = moment(time_now).endOf("d").utc().format();
let db = loadFB().firestore();
let query = db.collection('users').where('create_date','>=',user_history_start).where('create_date','<=',user_history_end);
let number ;
return query.get().then( docs=>{
number = docs.size
return number
})
}
i want output
data 2020-02-24
index 11 < (firestore given data)
but output
data 2020-02-24
index promise{<pending>} < (firestore given data)
Give me a good solution.
Upvotes: 1
Views: 90
Reputation: 1731
I guess you can't print a promised value in render, set the state and print it instead?
constructor() {
super();
this.state = {
index: null
}
}
getIndex = (date) => {
// --------- update ----------
UserAction.getIndex(date).then(date_total => this.setState({ index: date_total }))
}
componentDidMount() {
const date = "2020-02-24"
// --------- update ----------
this.getIndex(date)
}
render() {
console.log("index", this.state.index)
// will first print null,
// then print the index when the promise is done (re-rendered due to state change)
}
You may want to read this as a reference.
Upvotes: 2