I have been working on a blog application that utilizes ngrx for state management. Currently, there are two main objects stored in the application:
{
"posts": [...],
"users": [...]
}
Now, I am looking to create a separate component specifically for displaying individual posts (selected-post.component). To achieve this, I attempted to select the post entity based on its ID using the following selector:
export const selectPostById = (id: string) => createSelector(
selectEntities,
entities => entities[id]
);
Then, within the component, I retrieved the post using:
postId: string = localStorage.getItem("_selectedPostId");
selectedPost: Observable<Post> = this.store.select(selectPostById(postId));
To display the selected post in the view, I utilized the following code:
<ng-container *ngIf="selectedPost | async">
<div class="post text-light">
<div class="p-title fs-3">{{(selectedPost | async).title}}</div>
<div class="p-image">
<img [src]="(selectedPost | async).imageSrc">
</div>
<div class="p-cont fs-5">
{{(selectedPost | async).content}}
</div>
<div class="p-category float-start fs-6">
<a class="p-1" href="categories/category" *ngFor="let ct of (selectedPost | async).categories">
{{ct}}
</a>
</div>
// additional post details...
</ng-container>
However, I encountered an issue where the post was not displayed and received the error message in the console:
ERROR TypeError: Cannot read properties of undefined (reading: '1')
Despite selecting the post with the ID "1" which is present in the state as confirmed by redux devtools.
Looking for any suggestions or insights on resolving this issue.
EDIT: Here is the relevant reducer code:
// Reducer code...