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

How to map over users and display them in class based react component?

I’m trying to create a pie chart, where I map over the users and get the points and names for each of them. But something is wrong in the bellow code, and I can’t find it.

import React, { Component } from 'react';
import CanvasJSReact from './canvasjs.react';
import axios from 'axios';
var CanvasJS = CanvasJSReact.CanvasJS;
var CanvasJSChart = CanvasJSReact.CanvasJSChart;
 
class Dashboard extends Component { 
    constructor(props) {
        super(props);
        this.state = {
            users: [],

        };

    }
    componentDidMount() {
        axios
        .post("http://127.0.0.1:8000/api/v1/users/get_users", {
            company_id: localStorage.getItem("company_id")
        })
        .then((response) => {
            const s = response.data.users;
            this.setState(s);
            
        });
      }
    render() {
        
        console.log(this.state)
        const options = {
            animationEnabled: true,
            exportEnabled: true,
            theme: "dark2", // "light1", "dark1", "dark2"
            title:{
                text: "Trip Expenses"
            },
            data: [{
                type: "pie",
                indexLabel: "{label}: {y}%",        
                startAngle: -90,
                dataPoints: [
                    this.state.users.map((user) =>(
                        { y:user.points, label:user.name}
                    ))
    
                ]
            }]
        }
        
        return (
        <div>
            <CanvasJSChart options = {options}/>
        </div>
        );
    }
}
 
export default Dashboard;

when I console log the state, I can see the users are stored there

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 :

array.map, already returns an array, you don’t need to put it inside square brackets, like this:

dataPoints: [
              this.state.users.map((user) =>(
                { y:user.points, label:user.name}
              ))
            ]

Simply this should be enough:

dataPoints:  this.state.users.map((user) =>(
                 { y:user.points, label:user.name}
             ))
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