0

So, this is my code. I have a simple question just about how I can use the state element with indexin key? In this case I need to set the different values for different data index elements.

import React, { Component } from 'react';
import {Doughnut} from 'react-chartjs-2';

class Chart extends Component {
    constructor(props) {
        super(props);

        this.state = {
            labels: ["All", "Done", "Active"],
            datasets: [{
                label: "Todos",
                backgroundColor: 'grey',
                borderColor: 'green',
                data: [0, 0, 0]
            }]
        };
    }

    getTodosList = (todos) => {
        const all = [];
        const active = [];
        const done = [];

        todos.filter(todo => {
            if (todo.status === 'active') {
                active.push(todo);
            } else if (todo.status === 'all') {
                all.push(todo);
            } else if (todo.status === 'done') {
                done.push(todo);
            }
        });

        this.setState({
            datasets[0].data[0]: all, // error
            datasets[0].data[1]: active, // error
            datasets[0].data[2]: done // error
        });
    }

2 Answers 2

1

It's simple:

this.setState({
    datasets: [...this.state.datasets,
        {
            data: [all.length, active.length, done.length]
        }
    ]
});

Start to think like Redux think. Use pure functions. It's will help you. Also I understand based on your starts data - you probably need to use the length of your items...

Sign up to request clarification or add additional context in comments.

Comments

0

The setState function doesn't know which object it has to replace with your code. You're also not accessing the datasets variable properly, it should be this.state.datasets. You could do something like:

let datasets = this.state.datasets.slice();
datasets[0].data[0] = all;
datasets[0].data[1] = active;
datasets[0].data[2] = done;
this.setState({datasets});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.