Home > Back-end >  Redux Selector function returns error if not named correctly
Redux Selector function returns error if not named correctly

Time:11-23

I have this selector in my redux todo app:

export const selectTodoSlice = (state) => state.todoReducer;

And I have to name this state.todoReducer the same way I have defined my reducer in store:

import todoReducer from "../features/todo/todoSlice";
const store = configureStore({
  reducer: {
    todoReducer,
  },
});

...otherwise I'll get errors about some .map() functions.

So I was wondering if this is a convention and rule that this part of the return function in selectors — state.todoReducer — must always be the same as the reducer you name and pass into your store?

CodePudding user response:

When you pass { reducer: { todoReducer } } to configureStore, redux creates a corresponding property in state.

createStore({
  reducer: {
    todoReducer: (state, action) => { ... },
  }
})

// redux state
{
  todoReducer: {
    // whatever todoReducer returns
  }
}

You get a property in state for each property in reducer:

createStore({
  reducer: {
    todoReducer: (state, action) => { ... },
    someOtherReducer: (state, action) => { ... }
  }
})

// redux state
{
  todoReducer: {
    // whatever todoReducer returns
  },
  someOtherReducer: {
    // whatever someOtherReducer returns
  }
}

Your selector is returning a named property of the state object. If that named property does not exist in state, the selector will return undefined. If subsequent code is expecting an array and attempts to invoke map on it you'll get errors.

consider:

const state = {
  todoReducer: ["one", "two", "three"]
}

// this works
const todo = state.todoReducer; // array
const allCaps = todo.map(item => item.toUpperCase());
// ["ONE", "TWO", "THREE"]

// this doesn't
const notThere = state.nonexistentProperty; // undefined
const boom = notThere.map(item => item.toUpperCase()); // error
  • Related