Reputation: 705
So i have this method in container component:
getProfilesOptions = () => {
const result = firebase.firestore().collection('roles').get().then(snapshot => {
const options = []
snapshot.docs.forEach(doc => {
options.push({ value: doc.id, label: doc.data().profile })
//console.log(doc.id) - everything ok, i'm fetching data correctyly
});
return options
})
console.log(result)//here i have pending result in debugger
return result
}
then, i'm passing link into child...child...child component.
Then i some child i want to call it, and get array as a result, and then set the state:
componentDidUpdate() {
if(this.state.isFocused && !this.state.options){
const options = this.props.getOptions()
this.setState({
options: options
})
}
}
Can i have a solution of this problem? Ofcourse i can pass props as result instead of props ref to the method, but can i use the method? How to improve getProfilesOptions?
Upvotes: 0
Views: 82
Reputation: 691
You should wrap your firebase call in a Promise, because this is an async call.
getProfilesOptions = () => {
return new Promise(resolve => {
firebase.firestore().collection('roles').get().then(snapshot => {
const options = []
snapshot.docs.forEach(doc => {
options.push({ value: doc.id, label: doc.data().profile })
//console.log(doc.id) - everything ok, i'm fetching data correctyly
});
resolve(options)
})
}
}
And get the result in your component with .then()
componentDidUpdate() {
if(this.state.isFocused && !this.state.options){
this.props.getOptions().then(options => {
this.setState({
options: options
})
})
}
}
You can read more about Javascript Promises here
Upvotes: 3