Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngrx dealing with nested array in object

I am learning the redux pattern and using ngrx with angular 2. I am creating a sample blog site which has following shape.

export interface BlogContent {
  id: string;
  header: string;
  tags: string[];
  title: string;
  actualContent: ActualContent[];
}

and my reducer and actions are as following:

import { ActionReducer, Action } from '@ngrx/store';
import * as _ from 'lodash';
export interface ActualContent {
  id: string;
  type: string;
  data: string;
}

export interface BlogContent {
  id: string;
  header: string;
  tags: string[];
  title: string;
  actualContent: ActualContent[];
}

export const initialState: BlogContent = {
  id: '',
  header: '',
  tags: [],
  title: '',
  actualContent: [],
};

export const ADD_OPERATION = 'ADD_OPERATION';
export const REMOVE_OPERATION = 'REMOVE_OPERATION';
export const RESET_OPERATION = 'RESET_OPERATION';
export const ADD_IMAGE_ID = 'ADD_IMAGE_ID';
export const ADD_FULL_BLOG = 'ADD_FULL_BLOG';
export const ADD_BLOG_CONTENT_OPERATION = 'ADD_BLOG_CONTENT_OPERATION';
export const ADD_BLOG_TAG_OPERATION = 'ADD_BLOG_TAG_OPERATION';

export const blogContent: ActionReducer<BlogContent> = (state: BlogContent= initialState, action: Action ) => {
    switch (action.type) {
      case  ADD_OPERATION :
        return Object.assign({}, state, action.payload );
      case  ADD_BLOG_CONTENT_OPERATION :
        return Object.assign({}, state, { actualContent: [...state.actualContent, action.payload]});
        case  ADD_BLOG_TAG_OPERATION :
        return Object.assign({}, state, { tags: [...state.tags, action.payload]});
      case REMOVE_OPERATION :
        return Object.assign({}, state, { actualContent: state.actualContent.filter((blog) => blog.id !== action.payload.id) });
      case ADD_IMAGE_ID : {
        let index = _.findIndex(state.actualContent, {id: action.payload.id});
        console.log(index);
        if ( index >= 0 ) {
          return  Object.assign({}, state, {
            actualContent :  [
              ...state.actualContent.slice(0, index),
              action.payload,
              ...state.actualContent.slice(index + 1)
            ]
          });
        }
        return state;
      }
      default :
        return state;
    }
};

and this is working fine but i am not sure if its the right approach or should i somehow separate the ActualContent into its own reducer and actions and then merge them. Sorry if this post does not belong here and you can guide me where should put this post and i will remove it from here. Thanks in advance.

P.S. I have done some research but couldnt find any article that has complex nested objects so that i can refer. Please add any useful blog links of ngrx or related topic which can help me out.

like image 849
fastAsTortoise Avatar asked Apr 27 '17 21:04

fastAsTortoise


1 Answers

Instead of having a nested structure

export interface BlogContent {
  id: string;
  header: string;
  tags: string[];
  title: string;
  actualContent: ActualContent[]; <------ NESTED
}

You should have a normalized state.

For example here you should have something like :

// this should be into your store
export interface BlogContents {
  byId: { [key: string]: BlogContent };
  allIds: string[];
}

// this is made to type the objects you'll find in the byId
export interface BlogContent {
  id: string;
  // ...
  actualContentIds: string[];
}

// ----------------------------------------------------------

// this should be into your store
export interface ActualContents {
  byId: { [key: string]: ActualContent };
  allIds: string[];
}

export interface ActualContent {
  id: string;
  // ...
}

So if you try to populate your store it'd look like that :

const blogContentsState: BlogContents = {
  byId: {
    blogContentId0: {
      id: 'idBlogContent0',
      // ...
      actualContentIds: ['actualContentId0', 'actualContentId1', 'actualContentId2']
    }
  },
  allIds: ['blogContentId0']
};

const actualContentState: ActualContents = {
  byId: {
    actualContentId0: {
      id: 'actualContentId0',
      // ...
    },
    actualContentId1: {
      id: 'actualContentId1',
      // ...
    },
    actualContentId2: {
      id: 'actualContentId2',
      // ...
    }
  },
  allIds: ['actualContentId0', 'actualContentId1', 'actualContentId2']
};

In your logic or view (for example with Angular), you need your nested structure so you can iterate over your array and thus, you don't want to iterate on a string array of IDs. Instead you'd like actualContent: ActualContent[];.

For that, you create a selector. Every time your store change, your selector will kicks in and generate a new "view" of your raw data.

// assuming that you can blogContentsState and actualContentsState from your store
const getBlogContents = (blogContentsState, actualContentsState) =>
  blogContentsState
    .allIds
    .map(blogContentId => ({
      ...blogContentsState.byId[blogContentId],

      actualContent: blogContentsState
        .byId[blogContentId]
        .actualContentIds
        .map(actualContentId => actualContentsState.byId[actualContentId])
    }));

I know it can be a lot to process at the beginning and I invite you to read the official doc about selectors and normalized state

As you're learning ngrx, you might want to take a look into a small project I've made called Pizza-Sync. Code source is on Github. It's a project were I've done something like that to demo :). (You should also definitely install the ReduxDevTools app to see how is the store).

I made a small video focus only on Redux with Pizza-Sync if you're interested : https://youtu.be/I28m9lwp15Y

like image 127
maxime1992 Avatar answered Sep 22 '22 15:09

maxime1992