0
votes

I have an NGRX state setup that is an object of values. The value keys are numbers (1-5) with a boolean value.

state.ts

export interface State {
  1: boolean;
  2: boolean;
  3: boolean;
  4: boolean;
  5: boolean;
}

export const initialState: State = {
  1: true,
  2: true,
  3: true,
  4: true,
  5: true,
}

I also have an action that is getting passed the object number value through it. So in my reducer, I am grabbing the number value, finding that value in the object, and switching the boolean. However, I am running into an issue where I can't select the object key in my reducer function without actually typing out the physical number.

action.ts

export const changeButtonState = createAction(
  '[Bingo Actions] Change Button State',
  (payload: number) => ({payload}),
);

reducer.ts

export const reducer = createReducer(
  initialState,
  on(BingoActions.changeButtonState, (state, action) => {
    return {
      ...state,
      action.payload: !state[action.payload],
    };
  })
);

How can I access the number value of an object without having to physically type the number in the reducer function?

2

2 Answers

1
votes

Computed property names for your object keys - https://ui.dev/computed-property-names/

export const stateKeys = {
  one: 1,
  two: 2,
  ...
export interface State {
  [stateKeys.one]: boolean;
  [stateKeys.two]: boolean;
...

Then to access the property with a computed name inside your reducer, the syntax is:

state[stateKeys.one]
0
votes

Forgot that this was an object in the state and just needed to adjust the reducer to add a bracket around the action.payload assignment.

Updated reducer.ts

export const reducer = createReducer(
  initialState,
  on(BingoActions.changeButtonState, (state, action) => {
    return {
      ...state,
      [action.payload]: !state[action.payload],
    };
  })
);