Your JavaScript Firestore file seems to have a logical issue in the getTotalNumberOfPeople function and your Svelte component code:
In the getTotalNumberOfPeople function, instead of returning the total count of detected people, you're returning an array of objects constructed from the data. Then, after retrieving that array, you attempt to set the people store with the array instead of a count which is what your homepage appears to expect.
Here are the parts where discrepancies occur:
Firestore file:
export let people = writable(0) // This suggests `people` is a count (number), not an array
// ...
getTotalNumberOfPeople().then((out) => {
if(out){
people.set(out) // here you are setting `people` store with an array which contradicts the initial definition
});
// ...
To fix this, you should change the line people.set(out) to people.set(out.length) in case you want to store the number of people detected.
Additionally, there is a call to setPeople() which is not defined anywhere in your provided code. If setPeople is meant to be a function, you should make sure it's defined or remove this line if it's unnecessary.
Svelte Homepage:
<script>
// ...
let totalNumberOfPeopleArray = $people // implies $people is an array
// ...
const unsubscribePeople = people.subscribe((value) => {
totalNumberOfPeopleArray = value; // since `people` was meant to be a count, this is incorrect usage
// ...
});
// ...
</script>
Since you initially planned for people to be a count of detections, you should not use it as if it's an array. The subscription should reflect this. For example:
const unsubscribePeople = people.subscribe((value) => {
up = 0;
down = 0;
// Since `people` is a count now, you don't loop over it.
// Instead, you should fetch the whole list if you need to calculate 'up' and 'down'.
// ... Calculate up and down based on latest data if needed
getCrowdnessIndicator();
});
If you indeed need the array of detected people in the Svelte component to calculate "up" and "down", you need to change the Firestore file to return and set the count correctly and potentially introduce another store for the list of detections.
Also, be sure that your unsubscribe functions properly clean up the subscriptions when the component is destroyed, which currently they do:
onDestroy(() => {
unsubscribeOccupants();
unsubscribeUnits();
unsubscribePeople();
unsubscribeCapacity();
});
Lastly, ensure that your components are properly reactive in Svelte; remember to use the $ symbol to access the value of stores, like $people, when needed inside your HTML markup for reactivity, but not in your script logic for subscriptions.
By fixing these issues, you should be able to have a reactive display of the number of detected people from Firestore in real-time in your Svelte web app.