react-treebeard icon indicating copy to clipboard operation
react-treebeard copied to clipboard

State mutation in readme example

Open nicolas-despres opened this issue 8 years ago • 2 comments

Hi First thanks for the great library. Quick question, from the react doc:

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

However we do mutate the state in the doc example of this repo:

if(this.state.cursor){this.state.cursor.active = false;}

I tried using setState with a spread operator but it would not work: this.setState({ cursor: {...this.state.cursor, active:false} });

So it seems that the cursor is used as a pointer to the selected node. It works and may be completely valid but I guess it confuses me. Is it the normal way to go?

Thanks

nicolas-despres avatar Jan 30 '17 17:01 nicolas-despres

@nicolas-despres I too got confused by the example that goes against official recommendation. Hope @alexcurtis will shed some light on it.

Meanwhile you can try this snippet from my code

  onToggle(n, toggled) {
    if (this.state.cursor) {
      const cursor = this.state.cursor;
      cursor.active = false;
      this.setState({ cursor });
    }
    const node = n;
    node.active = true;
    if (node.children) {
      node.toggled = toggled;
    }
    this.setState({ cursor: node });
  }

talha131 avatar Feb 07 '17 13:02 talha131

💯 This is an excellent implementation of a tree view in React. I'd love to see the official example have the state contain data and also not mutate the state. I may just make a pull request myself to see if there's interest in this.

therealparmesh avatar Dec 30 '17 19:12 therealparmesh