T
T
tekleworm2018-03-19 12:26:05
JavaScript
tekleworm, 2018-03-19 12:26:05

Can't call state?

There is a state

constructor() {
        super();
        this.state = {
            data: {},
            trainer: [],
            diagram: this.chartData(),
        };
    }

Data has a numeric field boys and girls, I want to call them in the chartData function
chartData() {
        console.log(this.state.data.boys);
        return {
            labels: ['Boys', 'Girls'],
            datasets: [
                {
                    label: 'My First dataset',
                    fillColor: 'rgba(220,220,220,0.2)',
                    strokeColor: 'rgba(220,220,220,1)',
                    pointColor: 'rgba(220,220,220,1)',
                    pointStrokeColor: '#fff',
                    pointHighlightFill: '#fff',
                    pointHighlightStroke: 'rgba(220,220,220,1)',
                    data: [3, 0],
                },
            ]
        }
    }

But gives error TypeError: this.state is undefined. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Aleksandrovich, 2018-03-19
@tekleworm

constructor() {
        super();
        this.state = {
            data: {},
            trainer: [],
            diagram: this.chartData(),
        };

this.chartData=this.chartData.bind(chartData)
    }

D
DarthJS, 2018-04-16
@DarthJS

Or declare chartData as an arrow function
chartData = () => {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question