0
votes

I have an app that displays blogs using ngrx

The main root state is as follows

import { Blog } from '../models/blog';

export interface AppState {
  readonly loaded: boolean;
  readonly blogs: {[key:number]:Blog}
}

export const initialState:AppState = {
  loaded: false,
   blogs: {}
}

I also have a feature module set up to administrate the blogs

StoreModule.forFeature('crudBlog', reducers)

What I'm wondering about now is; when I want to update, delete etc. a blog how do I get access to the AppState (root state) of my store from the feature reducer file

So I can do something like this;

function handleBlogUpdatedAction(state, action){
    const index = action.payload.index;
    const newState = Object.assign({}, rootState);
    newState[index] = action.payload.blog
return newState;
}

Or is there a better way?

1

1 Answers

1
votes

ngrx state is suppose to be immutable, you are changing the state with by assigning it newState[index] = action.payload.blog.

So for example, this is how your reducer could look like:

export function reducer(
  state = initialState,
  action
) : BlogState {
    switch (action.type) {
        case UPDATED_BLOG_SUCCESS: {
            const blog = action.payload;
            const entites = {
                ...state.entities,
                [blog.id]: blog
            };

            // below is how your new state is returned using the spread operator
            return {
                ...state,
                entities
            };
        }
    }
}

Where initialState is:

export interface BlogState {
    entities: { [id: number]: Blog };
    loaded: boolean;
    loading: boolean;
}

export const initialState : BlogState = {
  entities: {},
  loaded: false,
  loading: false,
};