In my React App I'm making I'm trying to get the first Season, the default season, in the database to be returned, if there isn't a season selected. It should then return all the sessions connected to that seasion and add them to the state.
For some reason defaultSeason
isn't resolving before the then()
function fires.
const getDefaultSeason = (uid) =>
{
return database.ref(`subs-tracker/users/${uid}/seasons/`)
.orderByChild('seasonName').limitToFirst(1).once('value')
.then((snapshot) =>
{
let season;
snapshot.forEach((childSnapshot) =>
{
season = childSnapshot.key;
})
return season;
});
};
export const startSetSessions = ( seasonUuid ) =>
{
if ( seasonUuid )
{
return ( dispatch, getState ) =>
{
const uid = getState().auth.uid;
return database.ref(`subs-tracker/users/${uid}/sessions/${seasonUuid}`)
.once('value')
.then((snapshot) =>
{
const sessions = [];
snapshot.forEach((childSnapshot) =>
{
sessions.push(
{
id: childSnapshot.key,
...childSnapshot.val()
});
});
sessions.forEach((session) =>
{
const index = sessions.findIndex( (currentSession) =>
{
return session.id === currentSession.id;
});
sessions[index] = {...session, recordType: 'SESSION'}
})
dispatch(setSessions( sessions ));
});
}
}
else
{
return ( dispatch, getState ) =>
{
const uid = getState().auth.uid;
const sessions = [];
const defaultSeason = getDefaultSeason(uid);
defaultSeason // this is not resolving first
.then(database.ref(`subs-tracker/users/${uid}/sessions/${defaultSeason}`)
.once('value')
.then((snapshot) =>
{
snapshot.forEach((childSnapshot) =>
{
sessions.push(
{
id: childSnapshot.key,
...childSnapshot.val()
});
});
sessions.forEach((session) =>
{
const index = sessions.findIndex( (currentSession) =>
{
return session.id === currentSession.id;
});
sessions[index] = {...session, recordType: 'SESSION'}
})
dispatch(setSessions( sessions ));
}));
}
}
}
CodePudding user response:
The issue is that you're trying to use defaultSeason
variable in the then callback
.
Here is how you can fix this
export const startSetSessions = (seasonUuid) => {
if (seasonUuid) {
...
} else {
return (dispatch, getState) => {
const uid = getState().auth.uid;
const sessions = [];
getDefaultSeason(uid)
.then((defaultSeason) => {
...
});
}
}
}
CodePudding user response:
The issue has been addressed above. Except replacing the defaultSeason
into getDefaultSeason(uid)
as the answer above.
getDefaultSeason(uid)
.then(database.ref(`subs-tracker/users/${uid}/sessions/${defaultSeason}`)
.once('value')
You can also put an await
in your code such that
const defaultSeason = await getDefaultSeason(uid) // This should resolve the issue with minimum change of source code