by gernb · 3y ago · 0 comments
A simple example might be a tree structure. Think of folders and files on your computer. So first I go implemented a file system and I have folders that are a collection of files and folders. This data structure is hierarchical.
Now I want to make a React based UI where the user can create and delete folders and files.
5 folders deep the user want's to add a file. According to all the react docs I'm not allowed to just add a file to that folder as that would be mutating data. Instead I need to make a new folder, copy all the old entries to it, put the new file in. But, since it's 5 level deep subfolder, by the same rule, I need to do the same with its parent (make a new parent, copy all the old entries except the old folder, put in the new folder that's holding the new file). Oh but we're 5 levels deep so repeat all the way up the tree.
React people will often say "flatten your data" but that's the entire point, I shouldn't have to change my model to satisfy the UI library! I've already got working code without a UI. I just want to add a UI, not re-write all the other non-UI code.
I'm sure I just don't get it. Maybe a react expert will tell me how I use react without having to change my model.
setState(data.map { d-> d.tree.map { d2 -> ... } })
is the exact same thing as data[5][6][2][4].addChild(file)
setState(data)
React people will tell you to only use immutable objects, do copies, etc, but if your usecase requires mutating data, just mutate the damn data. It's not all or nothing. And even if you want to work with purely immutable data, you can work with lenses and have everything you want. With any language that has proper typing, you don't even need to build lenses with "keyed" names and can get the proper types.