Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redux Selector function returns error if not named correctly

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading