So I had a question about how to run rendering in react native after data is loaded from a database. In my code, I want to list prescriptions, but it keeps giving errors as it tries to load the prescription in the rendering function before executing the code that reaches out to firebase and gets the prescription data. How do I make it so that the rendering happens after the firebase data is gathered.
The easiest way to do this is to just have a loading
state in React, this can default to true
and once the data has been retrieved from Firebase you set to false. Then in your jsx you can return a loader or similar while the loading state is true and only render the rest of the screen that relies on the Firebase data once it's available and loading is set to false. Here's a minimal demo of this concept:
https://codesandbox.io/s/great-shockley-i6khsm?file=/src/App.js
import { ActivityIndicator, Text } from "react-native";
const App = () => {
const [loading, setLoading] = useState(true);
useEffect(() => {
// This is where you would have your Firebase function.
setTimeout(() => setLoading(false), 5000);
}, []);
if (loading) {
return <ActivityIndicator />;
}
return <Text>This is my app showing Firebase data</Text>;
};
export default App;
If you want to read a bit further and handle a potential error state if the Firebase function fails then here's a neat article to avoid an anti-pattern having a loading, success and error state. https://dev.to/tehaisperlis/the-loading-anti-pattern-7jj