0

I've been storing everything in arrays up until now, but after coming across this StachOverflow question about keyed object indexes and how traversing arrays can lead to a performance loss, I wanted to shift towards storing stuff as objects. I don't quite get the syntax however.

This reducer is meant to create an indexed object but it doesn't seem to work. How can I fix it to produce the desired object shape below?


type MsgPayload = {
  type: string;
  msgKey?: string;
  index?: number;
};

type IndexedMsgPayload = {
  [key: number]: MsgPayload;
};

const messengerSlice = createSlice({
  name: "messages",
  initialState,
  reducers: {
    emitMessage: (state, action: PayloadAction<MsgPayload | any>) => {
      state.total++;
      const indexedObj: IndexedMsgPayload = {
        0: {
          ...action.payload,
        },
      };
      action.payload[state.total] = indexedObj[0];
      state.messages = { ...state.messages, ...action.payload[state.total] };
    },
  },
});

I want to achieve something like this:

{
   1: { 
    type: 'type',
    msgKey: 'alert'
  },
}
sjsanc
  • 45
  • 4

1 Answers1

2

Redux Toolkit already has a createEntityAdapter API that does the work of defining and updating a normalized state structure for you:

markerikson
  • 63,178
  • 10
  • 141
  • 157