2

The error I'm getting is Cannot find name 'objectArray'.

interface StateInterface {
  objects: {
    objectArray: object[];
    selected: object;
  };
}

const InitialState: StateInterface = {
  objects: {
    objectArray: [],
    selected: {},
  },
};


const Reducer = (state: StateInterface, action: any) => {
  switch (action.type) {
    case 'SELECTED':
      return {
        ...state,
        objects: { ...state.objects, selected: action.value },
      };
    case 'ADD_OBJECT':
      return {
        ...state,
        objects: { ...state.objects, objectArray: objectArray.push(action.value )},
//                                                     ^---- Cannot find name 'objectArray'.ts(2304)
      };
    default:
      return state;
  }
};

I also tried

objects: { ...state.objects, objectArray:  ...action.value )},

1 Answer 1

3

Only the state object is in scope at that point (provided as an argument to the reducer), try switching objectArray for state.objectArray at the point you're getting the error.

But also, you'll need to append the value immutably for it to be correct (a rule of reducers), so you'll need to make that whole line something like:

objects: { ...state.objects, objectArray: [...state.objectArray, action.value]},

To create a new array with both the old values and the new value you're adding.

Sign up to request clarification or add additional context in comments.

1 Comment

objects: { ...state.objects, objectArray: [...state.objects.objectArray, action.value]}, did the trick thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.