Steve Winter
Steve Winter

Reputation: 125

React - Initialise state and access the state before first render

I have the following issue. I would like to initialise the state of my main component App where one of the state properties has to access another one.

Doing the following I get the this error - TypeError: Cannot read property 'items' of undefined.

 class App extends Component {
  state = {
    items: [
        'itemOne',
        'itemTwo',
    ],
    currentItem: this.state.items[0]
}

I assume that the state was not set yet, thus the items array doesn't exist. Setting the state of currentItem using componentDidMount() may solve the problem but then other errors might occur because currenItem is passed as prop to other components.

What is the most elegant, standard way you managing this?

Upvotes: 1

Views: 2268

Answers (2)

Tom Slutsky
Tom Slutsky

Reputation: 724

you can do it in the constructor:

 class App extends Component {
  constructor(props) {
    super(props);
    const items =  [
        'itemOne',
        'itemTwo',
    ]
    this.state = {
    items: items,
    currentItem: items[0];
  }
}

Upvotes: 1

kyun
kyun

Reputation: 10264

You can't set the state's value to another state before rendering. In this case, You can use the lifecycle componentDidMount().

class App extends Component {
  state = {
    items: ['itemOne', 'itemTwo'],
    currentItem: 'itemOne' || null //You can define the initial value or null
  }
  componentDidMount(){
    setState({...this.state, currentItem: this.state.items[0]});
  } 

Upvotes: 0

Related Questions