A
A
artemkazan2015-10-21 22:09:57
React
artemkazan, 2015-10-21 22:09:57

How do I write a redux reducer?

Hello everyone, I can’t figure out how to write a reducer so that it changes the visible property in nested data, that is, there is a tree-view, when you click on a tree element, visible should change, while opening the next nested element, etc.

email: {
    folderList: [ {
        name: 'Inbox',
        isSelected: false,
        isNested: true,
        visible: false,
        folderList: [ {
                name: 'SubFolder1',
                isNested: true,
                visible: false,
                folderList : [ {
                    name: 'SubFolder2',
                    isNested: true,
                    visible: false,
                    folderList: [ {
                            name: 'SubFolder3',
                            isNested: false,
                            visible: false
                    } ],
                    count: 5
                } ]
            }, {
                name: 'SubFolder1',
                isNested: false,
                visible: false
        } ]
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2015-10-22
@iNikNik

If you do everything right, then first you need to normalize the whole thing. To get a list of folders (I recommend storing id => entity in a hashmap):

folders: {
  '123': {
    id: 123,
    name: 'Inbox',
    isSelected: false,
    parentId: 123,
    visible: false,
  },
}

Actually after that, creating a reducer will turn into a fairly simple task:
function folder(action, state = initialState) {
  switch(action.type) {
    case OPEN_FOLDER_ACTION:
      const nextFolders = _.mapValues(state.folders, folder => {
         // Устанавливаем флаг "выбрана" для выбранной папки
        if (folder.id === action.targetId) {
          return { ...folder, isSelected: true };
        }
         // Для дочерних папок устанавливаем флаг видимости
        if (folder.parentId === action.targetId) {
          return { ...folder, visible: true };
        }
        return folder;
      });
      return {
        ...state,
        folders: { ...nextFolders },
      };
  // ...
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question