actually I'm using NGRX (Redux for Angular). At the beginning I have started to store my entities as arrays inside my state. After reading some articles I want to store my entities as hashes while I think it is more performant accessing an entity of entities using the id instead of filtering an array.
But I'm actually unsure doing that the right ngrx way.
Feel free to check my (working - but best practice?) sample here: Ngrx Articles Sample
Inside the articles.component you will find an articleReducer and an ArticlesComponent, that will use the store to get all articles and to get one concrete article.
For each unsure part I have comment that with QUESTION x - ...
If you don't want to check the complete sample, here are the Question Snippets:
Question 0:
export const initialState: ArticleState = {
foo: 'bar',
articlesById: [], // QUESTION 0: What is a good usecase to hold an array with the id's when Object.keys(hash) will give the same?
articleEntities: {}
}
Question 1 + 2:
case GET_ALL_ARTICLES: {
// QUESTION 1: is this a good choice? Or is there a better alternative to create the hash?
const articleHash: { [id: number]: Article} = {};
action.payload.forEach(article => articleHash[article.id] = article);
return {
...state,
// QUESTION 2: is this a good choice? Or is there a better alternative?
articlesById: action.payload.map(article => article.id),
articleEntities: articleHash
}
}
Question 3:
// QUESTION 3 - Getting all articleEntities as Array for ngFor : is this a good choice? Or is there a better alternative?
this.articles$ = this.store.pipe(
select('articles', 'articleEntities'),
map(entities => Object.keys(entities).map(id => entities[id]))
);
Question 4:
const givenIdByRouterMock = 2;
// QUESTION 4 - Getting one concrete Article for given id : is this a good choice? Or is there a better alternative?
this.article$ = this.store.pipe(
select('articles', 'articleEntities'),
map(entities => entities[givenIdByRouterMock])
);
If I will update some article (for instance with id 2) using a new action, I want, that the component including the article will be updated.
Are this valid variants or are there better options, solutions? Feel free to fork the stackblitz sample with other variants/code snippets.
Thanks!