Uland
Uland

Reputation: 11

angular ngrx store update array item if id matches

I have array of calls. They have different keywords, and call has id which is call_id. Array is empty on begining. If array is empty or there is no call with incoming call id, then it have to add call to call array in state. In otherwise, when array in state has a call with incoming id, it will update matched call. Now initialState.calls[] is still empty

 export interface Call {
  timestamp: number;
  call_id: string;
  keywords: Keyword[];
}

 export const initialState: KeywordsModel = {
   version: '',
   calls: [],
   isOpen: false,
   lastUpdatedOn: Date.now()
 };

 export const reducer = createReducer(
   initialState,
   on(KeywordsWebSocketActions.messageReceived, (state, { message, timeReceived }) => ({
     ...state,
     ...message,
     lastUpdatedOn: timeReceived
   })),
   on(KeywordsWebSocketActions.keywordsPageOpened, state => ({ ...state, isOpen: true })),
   on(KeywordsWebSocketActions.messageCallReceived, (state, { call }) => ({ ...state, calls: (state.calls.map((existCall: Call) => (existCall.call_id === call.call_id) ? state.calls[existCall.call_id] : [...state.calls, call])),
  }),
  
  ))
 
 export function reducerFactory(state: KeywordsModel | null, actions: Action) {
   return reducer(state, actions);
 }

After messageCallReceived with map() is done STATE remains empty {}.

Please for hints.

Upvotes: 0

Views: 297

Answers (1)

Andrei
Andrei

Reputation: 11951

I'm not exacly sure about what you wanted to achieve, but most likely correct code would be this:

state.calls.map((existCall: Call) => (existCall.call_id === call.call_id) ? call: existCall)

this should update only one item in your array

Edit: full logic with update, and if none was updated - push new item

on(KeywordsWebSocketActions.messageCallReceived, (state, { call }) => {
   let wasUpdated = false;
   const newCalls = state.calls.map(c => {
      if( c.call_id == call.call_id) {
         wasUpdated = true;
         return call;
      } else {
         return c;
      }
   })
   if(!wasUpdated){
      newCalls.push(call);
   }
   return {
     ...state,
     calls: newCalls,
   }
})

Upvotes: 1

Related Questions