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
        }
    }
}

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄