Search code examples
reactjsscopeconstantsblock

React access const outside of block scope


Hi I am trying access a const which is assigned a value within the block scope of componentDidMount() and assign it within a different method but I am having difficulty achieving so. I have tried saving it to state, however 'something' is not defined within renderTable()

My code is as follows:

// Pseudo code:
class tableView extends Component {

  componentDidMount() {
    .......
      const something = 'blah';
      this.setState({something});
  }
  renderTable() {
    const tableData = [
      {
        name: 'Item 1',
        data: this.state.something,
      },

    ];

    return {
        ......
    };
  }

Are there any other approaches to allow me access the something const within renderTable()?


Solution

  • state = {
    tableData : [
          {
            name: 'Item 1',
            data: this.state.something,
          },
    
        ],
     something:'this is something on mount it will change to blah',
    
    }
    
    
     componentDidMount() {
    .......
      const something = 'blah';
      this.setState({something});
    }
    
      renderTable() {
       const {tableData} = this.state;
    
        return {
            ......
        };
      }
    

    access with this.state.tableData or use destructuring.