Search code examples
react-nativereduxreselect

How to encapsulate logic in a createSelector function?


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,
    }))
);


Solution

  • 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.