SolidJSS
SolidJSโ€ข3y agoโ€ข
12 replies
TorHammare

How to handle Reactivity for nested objects?

I have a tree structure which i want to render and have reactive to changes. The tree is in its own file and should not be mixed into solidjs or jsx stuff. When calling updateTree(node, id) the tree will update from that node (including) and outward the branch, meaning all nodes after that node needs to be updated/rerenderd.

Below is some simplified example code.
Thank you

interface treeNode {
  id:number,
  left:treeNode | null,
  right:treeNode | null
}

const root:treeNode = {
  id: 1,
  left: {
    id: 2,
    left: null,
    right: {
      id: 4,
      left: null,
      right: null
    }
  },
  right: {
    id: 3,
    left: null,
    right: null
  }
};

const [state, setstate] = createStore(root);

function update (node: treeNode): void {
  // What should I put in here?
  // Should I use produce?
  const path: ('left'|'right')[] = getPath(node); // finds all root.left.right.left or whatever from root to the specific node
  setstate(...path, node); // from example: setState("path", "to", "value", newValue); but i get error: A spread argument must either have a tuple type or be passed to a rest parameter.
};

const TreeTile:Component<{node:treeNode, update:(node: treeNode) => void}> = (props) => (
  <Show when={props.node.left && props.node.right} fallback={
    <button onClick={() => {
      updateTree(new TreeNode(props.node, getNewId())); // This will change everything on this node and branch of the tree
      props.update(props.node); // so here I'm updating the store/state to rerender everything from this branch.
    }}>props.node.id</button>
  }>
    <TreeTile node={props.node.left!} update={props.update}/>
    {props.node.id}
    <TreeTile node={props.node.right!} update={props.update}/>
  </Show>
);

render(() => <TreeTile node={state} update={update}/>, document.body);
Was this page helpful?