I have a lot trouble with async functions and assign to a variable on react-native.
So to put in context, I wanna retrieve a data from a database (firebase https://rnfirebase.io/database/usage), so I called a function database(), but I always get null. I realized that this function is asynchronous and I want to get sequentially the data from top to bottom. So I tested it out by printing my code and I got "2" before "1".
What I want is to print the data (from the database), but I get a null
I did many search on google and stackOverflow and I'm struggling on getting this data from asynchronous function.
So how I can I change my code to be able to print the value from the database
const [data, setData] = useState();
useEffect(() => {
database()
.ref(`/${id}`)
.once('value')
.then(snapshot => {
setData(snapshot);
console.log(snapshot); //I can see data that I want to retrieve
console.log(1);
});
}, []);
console.log(2);
console.log(data) // I WANT TO PRINT HERE WITH THE VALUE expected the data from firebase-database, but have null as value