I am currently working with the following function:
public GetExercisePosts(user: User): ExercisePost[] {
const exercisePosts = new Array<ExercisePost>();
firebase.firestore().collection('exercise-posts').where('created-by', '==', user.Id).onSnapshot((results) => {
results.forEach((postDoc) => {
const exercisePost = Deserializer.DeserializeExercisePost(postDoc);
if (exercisePost) {
exercisePosts.push(exercisePost);
}
});
});
return exercisePosts;
}
Another react component will make use of this function like so:
public async componentDidMount() {
const personalExercisePosts = this.exerciseService.GetExercisePosts(this.state.currentUser);
this.setState({ personalExercisePosts });
}
The functionality works perfectly for the initial call. However, I have noticed that the original GetExercisePosts
method is not triggered again when the snapshot changes. This behavior is expected as componentDidMount
only gets executed once in a component's lifecycle. Despite this, the snapshot function does get called whenever there are changes, which is evident when a new record is added through the Firestore admin console.
Is there a way to observe and respond to changes made to the snapshot? Maybe by setting up the snapshot to emit a change event that the component can listen for. While I am aware that introducing Redux could solve this issue, I would prefer to explore alternative solutions at this point.