Home > front end >  How to encapsulate logic in a createSelector function?
How to encapsulate logic in a createSelector function?

Time:05-02

I have a React Native app using Redux.

I want to be able to add an entry at the beginning of this list of projects but it is not working.

Part of code provided below.

This is the error I get:

TypeError: undefined is not an object (evaluating 'projects.list.push')

Im not show of the correct syntax here??

Thanks in advance.

initialState: {
    list: [],
    loading: false,
    lastFetch: null,
  },


export const getPickerList = createSelector(
  (state) => state.entities.projects,
  (projects) => projects.list.push({ project_id: 0, project_name: "[All]" }),
  (projects) =>
    projects.list.filter((project) => ({
      project_id: project.project_id,
      project_name: project.project_name,
    }))
);

CodePudding user response:

I think you actually want to do this:

export const getPickerList = createSelector(
  (state) => state.entities.projects,
  (projects) => {
    const projectsWithPrefix = [
      { project_id: 0, project_name: "[All]" },
      ...projects
    ];
    // you could filter here as well before returning
    return projectsWithPrefix 
  }
);

but honestly I have no idea what you were trying with that .filter there.

Generally, you cannot "chain" as you were thinking you were doing. All the return values of all functions except for the last one are passed as arguments into the last function, not the next one.

CodePudding user response:

You've got two bugs here, plus I think there's a conceptual problem.

The first is that you are actively mutating projects.list, by calling projects.list.push(). You must never mutate state when using Redux.

The second issue is that all input selectors get called with the same arguments. So, if you call selectSomeThing(state, "a', 42), all input selectors will get called with state, "a", 42.

That means that the second input selector's first argument is actually state, not projects.

The other problem is that a selector isn't the right place to "add" anything. That sounds like a state update, and all state updates must happen in reducers.

  • Related