Search code examples
reactjsstatesetstate

Cannot change hidden column state from true to false on setState


I'm using devexpress React table and you can hide and show columns via state.

I would like to change the state for hidden from true to false but I get an Uncaught Invariant Violation error.

I've tried to use setState but doesn't work.

class ResultsTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
        columns: [
            { name: 'agent', title: 'Agent' },
            { name: 'alertGroup', title: 'Alert Group', hidden:true },
            { name: 'manager', title: 'Manager', hidden:true }
            ],
        };
    }


    componentDidMount() {
        this.testAlert();
    }

    testAlert = () => {
        if (this.props.alertgroupColumn()) {
            this.setState({
                columns: [{ name: 'alertGroup', title: 'Alert Group', hidden:false }]
            })
        }
    }

Hidden should change from true to false.


Solution

  • I have another alternative to update your state

      class ResultsTable extends Component {
            constructor(props) {
                super(props);
                this.state = {
                columns: [
                    { name: 'agent', title: 'Agent' },
                    { name: 'alertGroup', title: 'Alert Group', hidden:true },
                    { name: 'manager', title: 'Manager', hidden:true }
                    ],
                };
            }
    
    
            componentDidMount() {
                this.testAlert();
            }
    
            testAlert = () => {
                if (this.props.alertgroupColumn()) {
    //---- get the columns from state 
       let columns = JSON.parse(JSON.stringify(this.state.columns))
     columns[1].hidden = false
     this.setState({
          columns:columns 
        })  
                    this.setState({
                        columns: [{ name: 'alertGroup', title: 'Alert Group', hidden:false }]
                    })
                }
            }