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.
Why not? You don’t have any
questionsininitialState, so your questions gonna be populated only after you run fetchQuestions…If you do:
that should be sufficient to bypass this error