Reputation: 597
i'm using firebase and react hooks, my problem is that I need to check if the driverId that i have is still in the drivers list, but the problem is that inside the event, inputs.driverId is null, even if it already have a value, and if a "print" the inputs variable all the flelds are like when i declared the initial state.
const initialState = {
driverId:'',
drivers: []
};
const [inputs, setInputs] = useState(initialState);
const getDrivers = () => {
const self = this;
const nameRef = firebase.database().ref().child('drivers').orderByChild('status');
nameRef.on('value', snapshot => {
var drivers = snapshot.val();
setInputs(inputs => ({...inputs, ['drivers']: drivers}));
console.log('dtiverId', inputs.driverId) // console response: dtiverId
})
}
anyvody that can help me, i need when the event excutes check if the select driver (driverId) is still in the list, but when i check driverId i get null, only inside the event
Upvotes: 0
Views: 1225
Reputation: 101
The firebase realtime database works asynchronously. You should make use of async await or promises to get the data.
The examples in the firebase docs show how to get the data using promises.
Upvotes: 0
Reputation: 405
firebase.database()
is an asynchronous call. You need to add async and await like so
const getDrivers = aysnc () => {
const self = this;
const nameRef = await firebase.database().ref().child('drivers').orderByChild('status');
nameRef.on('value', snapshot => {
var drivers = snapshot.val();
setInputs(inputs => ({...inputs, ['drivers']: drivers}));
console.log('dtiverId', inputs.driverId) // console response: dtiverId
})
}
What is happening in your code is that you are trying to use driverId before it is returned from firebase (which is why it is null). Async will block until firebase returns then your code will resume executing.
Upvotes: 2