(reactassign Firebase Snapshot To A Variable Outside Of The Function
Hi i am trying to get the data from my database, in componentDidMount(), it works fine with this : componentDidMount() { firebase.database().ref('/users/' + user.uid).once('value
Solution 1:
classSearchextendsReact.Component {
constructor(props) {
super(props)
this.state = {
films: [],
isLoading: false,
userData: null
}
this.searchedText = ""this.localData=null;
}
componentWillMount() {
user = firebase.auth().currentUser;
firebase.database().ref('/users/' + user.uid).once('value').then(snapshot => {
pro = snapshot.val()
this.setState({userData: pro});
});
this.setState({ isLoading: true })
getFilmsFromApiWithSearchedText().then(data =>this.setState({ films: data.results }))
this.setState({
films: data.results,
isLoading: false
})
console.log(this.state.userData)
}
_displayLoading() {
if (this.state.isLoading) {
return (
<Viewstyle={styles.loading_container}><ActivityIndicatorsize='large' /></View>
)
}
}
_signOut() {
firebase.auth().signOut();
}
_displayDetailForFilm = (idFilm) => {
this.props.navigation.navigate("FilmDetail", { idFilm: idFilm })
}
render() {
return (
<Viewstyle={styles.main_container}><StatusBarhidden = {false}backgroundColor="#F1D145"
></StatusBar><TouchableOpacityonPress={() => this._signOut()} style={styles.button} activeOpacity={0.8}>
<Textstyle={styles.button_text}>Déconnexion</Text></TouchableOpacity><Text>{user.uid}</Text><FlatListdata={this.state.films}keyExtractor={(item) => item.id.toString()}
renderItem={({item}) => <FilmItemfilm={item}displayDetailForFilm={this._displayDetailForFilm}/>}
/>
{this._displayLoading()}
</View>
)
}
}
this.setState({ isLoading: true })
getFilmsFromApiWithSearchedText().then(data =>this.setState({ films: data.results }))
this.setState({
films: data.results,
isLoading: false
})
console.log(this.state.userData)
}
Here is all the code i already do console.log(this.state.userData) it return null
Solution 2:
You have to setState inside the .then function.
Then you can access your value with this.state.userData.
It will be undefined just after mounting then defined when your fetch resolves, so integrate a mechanism that checks for that.
For your undefined problem, a simple solution would be that for instance:
render() {
return (
<View>{this.state.userData && this.state.userData.photo}</View>
)
}
Edit: also like Kai pointed out I am not sure you have access to this
instance inside .then
callback if you don't use arrow notation.
Solution 3:
Switch the anonymous function that you're passing to .then
to an arrow function to allow you to use the this
from the class scope.
Plenty of information elsewhere on this
Post a Comment for "(reactassign Firebase Snapshot To A Variable Outside Of The Function"