I'm making a React App for my Football team to keep track of Payments and Debts for each Member. I'm trying to search the database for Records and Sessions for each Season and delete a Member if no Records or Sessions are found. Currently it finds Records fine but the Sessions search has an inner loop which I cannot get to return true when a Session is found.
This is the code block (it can also be seen with the rest of my App on GitHub here. I use Firebase to store all my data.
export const startRemoveMember = ( playerUuid, seasonList ) =>
{
return (dispatch, getState) =>
{
const uid = getState().auth.uid;
const recordPromises = seasonList.map( (season) =>
database.ref(`subs-tracker/users/${uid}/debts_and_payments/${season.seasonUuid}`)
.once('value')
.then((records) =>
records.forEach((childRecord) => // breaks on true
childRecord.val().playerUuid === playerUuid
)
)
);
const sessionPromises = seasonList.map( (season) =>
database.ref(`subs-tracker/users/${uid}/sessions/${season.seasonUuid}`)
.once('value')
.then((sessions) =>
sessions.forEach((childSession) =>
childSession.val().playerList.forEach( (player) => // should break on true
player.playerUuid === playerUuid
)
)
)
);
const promises = recordPromises.concat(sessionPromises);
return Promise.all(promises).then(findings =>
findings.includes(true)
)
.then(cannotDelete =>
{
if (cannotDelete)
{
alert('Cannot Delete. Member has records');
return false;
}
else
{
alert('Deleted');
return database.ref(`subs-tracker/users/${uid}/members/${playerUuid}`)
.remove()
.then((ref) =>
{
dispatch(removeMember(playerUuid)); // Calls removeMember() function to remove the Member from the State of the App
return true; // To distinguish from false
}
);
}
});
};
};
I'm probably missing something basic. Any help you would be appreciated :)
CodePudding user response:
forEach
does not return anything, for this use case .some
is what you need. This iterates over an Array
and when it resolves to true it stops iterating and returns true
if it resolves to false
on every item it will return false