Reputation: 2035
Trying to wrap my head around how I could do this...
I have a view in React Native that I want to show/or hide based on some information from a server (using firebase.. not that it matters). I can do this successfully just returning a value, but if I add a database call that determines to return it, it does not work.
The problem is the query returns fast, but might not return exactly when the view loads. Therefore I think by the time that If Loop in my code below finally runs, it is too late. Is there a way once I have the information I need from the database whether or not to show the view, to ReRender the view, or reload it, so the view will show if the database returns true
I should also add the thing I am querying the database with some information from this.props passed into the component
My current logic was (this might not be syntax, but I think you'll get the idea of the question):
returnOtherComponent(){
/*
This is just psuedo code, as the web query is a big block of text that is uneeded
*/
DatabaseIsTrue = Returned True from Web
if(DatabaseIsTrue){
return (
<View>
<Text> HELLO! </Text>
</View>
);
}
}
render(){
return(
<View>
{this.returnOtherComponent()}
</View>
);
}
Upvotes: 0
Views: 71
Reputation: 739
you can use an ActivityIndicator before data is loaded.
constructor(props){
super(props)
this.state = {
loading: true,
listing: {},//this object contains list of data you are gonna load from server
}
this._decideContent = this._decideContent.bind(this);
}
_fetchFunction(){
fetch(...)
.then(...)
.then(...)
.then((response) => {
this.state = {
...this.state,
loading: false,//now that data is loaded, we don't need the spinner anymore
listing: {data you fetched from server},
}
})
}
//if data is loaded, this function returns your component, if not, it returns an activity indicator
_decideContent(){
let loading = this.state.loading;
if(loading){
this._fetchData();//call the function that fetches data
return(
<ActivityIndicator animating={loading} />
)
}
else{
return(
<YourComponentContaingData listing = {this.state.listing} />
)
}
}
render(){
return(
{this._decideContent()}
)
}
Upvotes: 0
Reputation: 3003
You should use your state object to update the view.
So when the server request is back, you update the component state by setState() and the component will redraw.
returnOtherComponent() {
if (this.state.DatabaseIsTrue) {
return (
<View>
<Text> HELLO! </Text>
</View>
);
} else {
return {}
}
}
componentDidMount: function() {
/*
This is just psuedo code, as the web query is a big block of text that is uneeded
*/
DatabaseIsTrue = Returned True from Web
this.setState({
DatabaseIsTrue: DatabaseIsTrue
})
}
render(){
return(
<View>
{this.returnOtherComponent()}
</View>
);
}
Upvotes: 1