Home > Software engineering >  How to map over users and display them in class based react component?
How to map over users and display them in class based react component?

Time:07-24

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

CodePudding user response:

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}
             ))
  • Related