Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using setState (Class components) as a beginner React developer

I’m asking a basic question but I’m a noob which couldn’t even find the answer in google so please be gentle 😉. I’m trying to use setstate and I have no idea why my state continue to be empty. Here is the code:

import React, {Component} from 'react';
import Ball from './Ball'

class Lottery extends Component{
    constructor(props){
        super(props);
        this.state = { nums : []};
        this.RenderNums = this.RenderNums.bind(this);
        this.RenderNums();
    }

    RenderNums(){
        let ballnum = this.props.ballnum;
        let maxnum = this.props. maxnum;
        let arrnums = Array.from({length: ballnum}, () => Math.floor(Math.random() * maxnum) +1);
        console.log(arrnums);
        this.setState({nums : arrnums});
    }
    

I’m trying to put my random number array in the state, for that I’m calling a function in the constructor, but after npm start and looking at the dev tools my state nums is an empty array. The random numbers array is created just fine and being printed to the console. Someone can tell what am I doing wrong by looking at the code? If necessary I’ll try to put it on codepen.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should not call setState or any side effect in constructor, as mentioned in the docs:

You should not call setState() in the constructor(). Instead, if your
component needs to use local state, assign the initial state to
this.state directly in the constructor

Instead, assign the initial state directly or use a dedicated lifecycle, you should try componentDidMount.

class Lottery extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nums: Array.from(
        { length: this.props.ballnum },
        () => Math.floor(Math.random() * this.props.maxnum) + 1
      ),
    };
  }

  // or
  RenderNums = () => {...}

  componentDidMount() {
    this.RenderNums();
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading