hussain ashraf
hussain ashraf

Reputation: 51

Pie chart not rendering in React using Chart

I am facing an issue with rendering a pie chart in a React component using the react-chartjs-2 library along with Chart.js. The data for the chart is fetched from an API, and the chart is expected to render once the data is available. However, despite the data being fetched successfully, the pie chart is not rendering on the screen.

// Dashboard.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useUser } from '../UserContext';
import { AppBar, Toolbar, Typography, Container, Box } from '@mui/material';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Pie } from 'react-chartjs-2';
ChartJS.register(ArcElement, Tooltip, Legend);
const Dashboard = () => {
  const { userData } = useUser();
  const [genderCount, setGenderCount] = useState([]);
  const [loading, setLoading] = useState(true);
  let maleCount = 0;
  let femaleCount = 0;

  useEffect(() => {
    axios
      .get('https://randomuser.me/api/?results=10')
      .then(response => {
        const users = response.data.results;
        console.log(users)
        // Iterate over the users to count genders
        users.forEach(user => {
          if (user.gender === 'male') {
            maleCount++;
          } else if (user.gender === 'female') {
            femaleCount++;
          }
        });

        // Update the state with gender count
        // setGenderCount([
        //   { gender: 'male', count: maleCount },
        //   { gender: 'female', count: femaleCount }
        // ]);
        setLoading(false);
        console.log('male',maleCount)
        console.log('female',femaleCount)

      })
      .catch(error => {
        console.error('Error fetching data:', error);
        setLoading(false);
      });
  }, []);

  // Extract data for the pie chart
 const data = {
    labels: ['Male', 'Female'],
    datasets: [
      {
        label: '# of Votes',
        data: [maleCount,femaleCount],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',

        ],
        borderWidth: 1,
      },
    ],
  };

  return (
    <Container>
      <AppBar position="fixed">
        <Toolbar>
          <Box sx={{ flexGrow: 1 }}>
            <Typography variant="h6" component="div">
              Your Logo
            </Typography>
          </Box>
          <Typography variant="h6" component="div">
            {userData && `Welcome, ${userData.username}!`}
          </Typography>
        </Toolbar>
      </AppBar>

      <Box sx={{ marginTop: '4rem', width: '80%', margin: 'auto' }}>
        <h2>Dashboard</h2>
        {  (
          <div>
            {/* Display other user information */}
            
            {/* Conditionally render pie chart when data is available */}
            {loading ? (
              <p>Loading...</p>
            ) : (
              <div>
                <h3>Gender Counts</h3>
                <Pie data={data}/>
              </div>
            )}
          </div>
        )}
      </Box>
    </Container>
  );
};

export default Dashboard;
Issue Details:

Verified that the data is being fetched correctly. The loading state is set to false when the data is available. Using the Pie component from the react-chartjs-2 library. Set width and height for the chart.

Problem Details: The pie chart doesn't appear on the screen even after ensuring that the data is fetched and the loading state is set to false. I've also tried adjusting the width and height of the chart, but it doesn't seem to resolve the issue.

Question: I would appreciate any insights or suggestions on why the pie chart is not rendering as expected. Are there any potential issues with my code that I might have overlooked?

Thank you for your help!

Upvotes: 0

Views: 378

Answers (1)

santra72
santra72

Reputation: 114

Your code is almost correct except a small issue. In line 51 you are passing maleCount and femaleCount.But these values does not exist here and that is what causing the problem.

Instead you need to pass the value of maleCount and femaleCount using genderCount state. You should be passing it like this:

data: [genderCount[0]?.count, genderCount[1]?.count]

Here is the corrected code:

// Dashboard.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { AppBar, Toolbar, Typography, Container, Box } from '@mui/material';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Pie } from 'react-chartjs-2';
ChartJS.register(ArcElement, Tooltip, Legend);
const Dashboard = () => {
  // const { userData } = useUser();
  const [genderCount, setGenderCount] = useState([]);
  const [loading, setLoading] = useState(true);
  let maleCount = 0;
  let femaleCount = 0;

  useEffect(() => {
    axios
      .get('https://randomuser.me/api/?results=10')
      .then((response) => {
        const users = response.data.results;
        console.log(users);
        // Iterate over the users to count genders
        users.forEach((user) => {
          if (user.gender === 'male') {
            maleCount++;
          } else if (user.gender === 'female') {
            femaleCount++;
          }
        });

        // Update the state with gender count
        setGenderCount([
          { gender: 'male', count: maleCount },
          { gender: 'female', count: femaleCount },
        ]);
        setLoading(false);
        console.log('male', maleCount);
        console.log('female', femaleCount);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
        setLoading(false);
      });
  }, []);

  // Extract data for the pie chart
  const data = {
    labels: ['Male', 'Female'],
    datasets: [
      {
        label: '# of Votes',
        data: [genderCount[0]?.count, genderCount[1]?.count], // ✅ Made changes here
        backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)'],
        borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)'],
        borderWidth: 1,
      },
    ],
  };

  return (
    <Container>
      <AppBar position='fixed'>
        <Toolbar>
          <Box sx={{ flexGrow: 1 }}>
            <Typography variant='h6' component='div'>
              Your Logo
            </Typography>
          </Box>
          {/* <Typography variant='h6' component='div'>
            {userData && `Welcome, ${userData.username}!`}
          </Typography> */}
        </Toolbar>
      </AppBar>

      <Box sx={{ marginTop: '4rem', width: '80%', margin: 'auto' }}>
        <h2>Dashboard</h2>
        {
          <div>
            {/* Display other user information */}

            {/* Conditionally render pie chart when data is available */}
            {loading ? (
              <p>Loading...</p>
            ) : (
              <div>
                <h3>Gender Counts</h3>
                <Pie data={data} />
              </div>
            )}
          </div>
        }
      </Box>
    </Container>
  );
};

export default Dashboard;

Upvotes: 1

Related Questions