Update Redux store with reducer recursively

Viewed 264

I’ve been working on a bit of a lazy load recursive tree view, and while I have the component level stuff working, I’m having a bit of difficulty trying to work out how to make it play nicely with redux. For simplicity, let’s say I have the following data structure in redux

[
    {
        id: 'myId1',
        value: 'Tree View top level 1',
        fetchedChildren: []
    },
    {
        id: 'myId2',
        value: 'Tree View top level 2',
        fetchedChildren: []
    },

    …and so on

]

I have my recursive component working so that when you click on an item, the relevant id is sent to the API and a collection of children is returned. Clicking myId2 would result in the data looking like this

[
    {
        id: 'myId1',
        value: 'Tree View top level 1',
        fetchedChildren: []
    },
    {
        id: 'myId2',
        value: 'Tree View top level 2',
        fetchedChildren: [
            {
                id: 'myId3',
                value: 'Tree View second level 1',
                fetchedChildren: []
            },
            {
                id: 'myId3',
                value: 'Tree View second level 2',
                fetchedChildren: []
            },
        ]
    },
]

and then the idea is that this could theoretically go on for infinity.

below is an example of my reducer that updates the store correctly from the above first example to the second (the tree is linked to data)

case FETCH_CHILDREN_SUCCESS:
    return {
        ...state,
        loading: false,
        error: null,
        data: state.data.map(leaf=> leaf.id === action.payload.id ? {
        ...leaf,
        value: leaf.value, 
        fetchedChildren: action.payload.fetchedChildren.map( child => {
            return {
            ...child,
            value: child.value
            }
        })
        } : leaf)
    };

This will work to populate fetchedChildren on the second level, but how do you do this recursively for subsequent levels? I took a look at the tree-view sample in the redux source code, and the way they are managing the data is to have a flat array that is linked by ids to identify parents. Is the above the wrong way to look at it, and should I be looking at doing this in a flat array like the redux example?

0 Answers
Related