[Functional Programming] Using Lens to update nested object

For example, in React application, we have initial state;

const data = {
    nextId: 4,
    todoFilter: 'SHOW_ALL',
    todos: [
        { id: 1, title: 'Hug Unicorn', completed: false },
        { id: 2, title: 'Mess with Texas', completed: false },
        { id: 3, title: 'Do Laundry', completed: true }
    ],
    ui: {
        filterGroups: {
            status: false
        }
    }
}

We have a toggle button, which everytime, it is toggle 'ui.filterGroups.status' to true/false.

Whenever we have to update nested object, we should always comes up a word 'Lens'!

Here is how to do it:

import { State, compose  } from 'crocks'
import {lensPath, lensProp, over, not} from 'ramda'
const { modify } = State

// ui -> filterGroups -> status

const lnsFilterGroups = lensPath(['ui', 'filterGroups'])
export const toggleFilterGroup = ({ group }) => {
    const lns = compose(
        lnsFilterGroups,
        lensProp(group)
    )

    return modify(over(lns, not))
}
原文地址:https://www.cnblogs.com/Answer1215/p/10731851.html