user6385799
user6385799

Reputation:

How to access from state another key inside the state in React

I try to learn React and I have an issue. I want to make an example myself from the tutorial.

import React, { Component } from 'react';

class MyComponent extends Component {
  state = {
    persons: [],
    firstPersons: 5,
    variables: {
      Id: '1',
      first: this.firstPersons,
      input: {},
    }
  }

  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

I put in render method a console.log(this.state).

I have this simple state in my page, and when I run the project I get the error:

Uncaught TypeError: Cannot read property 'firstPersons' of undefined

Please someone tell me what is wrong on my code?

Upvotes: 3

Views: 2122

Answers (2)

Michael Yurin
Michael Yurin

Reputation: 1060

You can't access the object inside of itself in JS. You should do:

import React, { Component } from 'react';

var myVar = 5;

class MyComponent extends Component {
  state = {
    persons: [],
    firstPersons: myVar,
    variables: {
      Id: '1',
      first: myVar,
      input: {},
    }
  }

  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

or

import React, { Component } from 'react';

class MyComponent extends Component {
  state = {
    persons: [],
    firstPersons: 5,
    variables: {
      Id: '1',
      input: {},
    }
  }

  componentWillMount() {
    this.state.variables.first = this.state.firstPersons;
    this.setState(this.state);
  }

  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

or if componentWillMount() is deprecated

import React, { Component } from 'react';

class MyComponent extends Component {
  state = {
    persons: [],
    firstPersons: 5,
    variables: {
      Id: '1',
      input: {},
    }
  }

  static getDerivedStateFromProps(props, state) {
    this.state.variables.first = this.state.firstPersons;
    this.setState(this.state);
  }


  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

Upvotes: 4

VersifiXion
VersifiXion

Reputation: 2282

I suggest you this syntax :

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor() {
    super();
    this.state = {
     persons: [],
     firstPersons: 5,
     variables: {
     Id: '1',
       first: this.firstPersons,
       input: {},
     }
  }

  render() {
   console.log('this.state', this.state);
   return (
      <div>
        <p>Hello React!!!</p>
      </div>
    );
  }
}

export default MyComponent;

Upvotes: -1

Related Questions