Search code examples
angularobjectreduxselectornew-operator

How to create new object in redux selector and return it


Is there a way, how to create new object in redux selector and return it? I was searching around the net, but found no answer.

something like this:

export interface UserModel {
    user: string,
    job: string,
    contact: string,
    sex: string //not saved in store model
}

 export const mySelector= createSelector(
    moduleState,
    state => {
       state.user,
       state.job,
       state.contact
       } as Partial<UserModel> //casting not possible
  );

store$.select(Selectors.mySelector).subscribe(partialUser => { //partialUser is void
    cons sex = 'M';
    const user = {...partialUser, ...sex} as UserModel //spread operator possible only for objects
    }

If there is no such option in selectors, how to create objects from state properties and subscribe to them? My store state model is created from BE DTOs, so I dont need to do the mapping, when getting data from BE, but for FE UI models, I need to create objects derived from interfaces from store state, and I want to aviod manual typing and mapping. (the name of the properties in store state object match with the interfaces). Maybe it is possible with keyof and Partial.


Solution

  • You have made errors in your attempts:

    1. if you have arrow function that returns object it needs to be in round brackets
    export const mySelector= createSelector(
      moduleState,
      state => ({
        user: state.user,
        job: state.job,
        contact: state.contact
      } as Partial<UserModel>)
    );
    
    1. you wanted to spread string instead of just adding sex field to partialUser
    store$.select(Selectors.mySelector).subscribe(partialUser => {
      //partialUser is void
      cons sex = 'M';
      const user = { ...partialUser, sex } as UserModel;
    }