How to show Chart when use data from redux?

Viewed 12

I have data from redux cart and I get some artribute from data redux in array. I try to get data success but chart still don't show.

File ChartProduct.js

import React, { useState, useEffect } from 'react';
import {
    PieChart,
    Pie,
    Tooltip
} from 'recharts';
import { useSelector } from "react-redux";

const ChartProduct = () => {
    const productCart = useSelector((state) => state.cart.cartItems);
    const [dataSale, setDataSale] = useState(productCart);

    useEffect(() => {
        setDataSale(dataSale.map((item) => ({
            name: item.product.title,
            qty: item.quantity
        })))
    }, [])
    
    return (
        <NoSsr>
            <h1>Show Chart</h1>
            <PieChart width={400} height={400}>
                <Pie
                    // dataKey="name"
                    dataKey={`${dataSale.name}`}
                    isAnimationActive={false}
                    data={dataSale}
                    cx={200}
                    cy={200}
                    outerRadius={80}
                    fill="#8884d8"
                    label
                />
                <Tooltip />
            </PieChart>
    );
};

export default ChartProduct;

Everyone can help me. Thank you so much

1 Answers

Hmmm, so you are setting dataSale state with productCart but right after you set it again in the useEffect hook with its own data.

Try this:

const productCart = useSelector((state) => state.cart.cartItems);
const [dataSale, setDataSale] = useState([]);

useEffect(() => {
    setDataSale(productCart.map((item) => ({
        name: item.product.title,
        qty: item.quantity
    })));
}, [productCart]);

This way every time the productCart changes dataSale gets the updates.

Also I just noticed that there is no closing tag for <NoSsr>

Related