How to access state.entities in reducers for createSlice in Typescript redux-toolkit

37 Views Asked by At
const questionsAdapter = createEntityAdapter<Question>({
  selectId: (question) => question.key,
});

const defaultValue: Question[] = [];
questions.map((question) => {
  defaultValue.push(question as Question);
});

const initialState = questionsAdapter.getInitialState();

const questionSlice = createSlice({
  name: "questions",
  initialState,
  reducers: {
    fetchQuestions(state) {
      questionsAdapter.upsertMany(state, defaultValue);
    },
    hideQuestion(state, action: PayloadAction<{ key: EntityId }>) {
      const { key } = action.payload;
      state.entities[key].isVisible = false;
    },
  }
});

At line state.entities[key].isVisible typescript is throwing below error Object is possibly 'undefined'.ts(2532) (property) entities: WritableDraft<Dictionary<Question>>

How do I solve this issue?

typescript should not throw any errors.

1

There are 1 best solutions below

1
antokhio On

Why not? You don’t have any questions in initialState, so your questions gonna be populated only after you run fetchQuestions…

If you do:

if (state.entities) {
   …
}

that should be sufficient to bypass this error