How to visualize using setIn()

I know there is a lot of confusion on how to use setIn to directly change a Variable (formerly called a Temporary State Variable)

It just dawned on me the correct way to visualize this so I get it right consistently.

Let's say you have a Variable called itemList which is an object array with the following format:

[
    {
        "item_name": "Parent #1",
        "id": "3f104224-10ca-459e-a3bc-f15ee38b46d7",
        "children": [
            {
                "item_name": "Child #1",
                "id": "737856d5-8b8a-4ed2-b06f-02526ef0a99f",
            },
            {
                "item_name": "Child #2",
                "id": "6ea7def5-f85f-403f-8ae8-aecf074a3e57",
            }
        ]
    },
    {
        "item_name": "Parent #2",
        "id": "6b6ee503-0364-4a9c-8ad7-2259b6b677d0",
        "children": [
            {
                "item_name": "Child #3",
                "id": "6977348b-78c8-4be3-92d9-d9c0b0f30dac",
            },
            {
                "item_name": "Child #4",
                "id": "8102aec3-65af-4976-a72e-229d3b69972a",
            }
        ]
    }
]

And you want to change the second element's first child's item_name to "Hello World". You would do this for a normal object array:

itemList[1].children[0].item_name = "Hello World"

To use setIn, just extract out each part and put that into an array:

itemList.setIn([1,"children",0,"item_name"],"Hello World")

image

Another example:

itemList[1] =  {
        "item_name": "Parent #1",
        "id": "3f104224-10ca-459e-a3bc-f15ee38b46d7"
}

Becomes:

itemList.setIn([1],  {
        "item_name": "Parent #1",
        "id": "3f104224-10ca-459e-a3bc-f15ee38b46d7"
})

So the trick is to write it out as if it were a normal assignment and then condense all parts after the variable name into an array in the first parameter of setIn and the value in the second parameter.

9 Likes