Search code examples
react-nativereact-native-chart-kit

Dynamic data not displaying in react native?


I trying the below logic to display dynamic data in my react native. But it only shows data one time, if I refreshes my app, it gives error again and again: Error is like undefined is not an object('data.map') kind of....Can anyone help me if the logic is wrong, I am missing something in my logic ?

The problem is like it hardly displays data one time sometimes.

const [chartData, setChartData] = useState({});

    const chart = () => {
        let status = [];
        let dates = [];
        let count = 0;
        let count1 = 0;
        let count2 = 0;
        let count3 = 0;
        let count4 = 0;

        fetch("<API CALL>")
        .then(res => res.json())
        .then(results => {
            for (const stats of results) {
                if (stats.status == "Open") {
                    count = count + 1;
                }
                else if (stats.status == "Closed") {
                    count1 = count1 + 1;
                }
                else if (stats.status == "Resolved") {
                    count2 = count2 + 1;
                }
                else if (stats.status == "In Process") {
                    count3 = count3 + 1;
                }
            }
            count4 = count3 + count2 + count1 + count;
            setChartData({
                    labels: ["Open", "Closed", "Resolved", "In Process"],
                    datasets: [
                        {
                            data: [count, count1, count2, count3]
                        }
                    ]
            })
        })
        console.log(chartData);
    }

    useEffect(() => {
        chart();
    }, []);
<BarChart
                    style={{ borderRadius: 16 }}
                    data={chartData}
                    width={screenWidth}
                    height={400}
                    chartConfig={chartConfig}
                    verticalLabelRotation={30}
                />

Data which is stored in monogdb atlas

_id:<RANDOM_ID>
name:"Jade Labs access"
request:"Dhanjay"
subject:"PI RPA"
category:"IT"
priority:"High"
desc:"RPA project"
location:"Pune"
status:"Resolved"
date:"2/23/2021"
__v:0
assign:"Dhanjay Bhardwaj"

Solution

  • try if this works

       {chartData.datasets != undefined ? (<BarChart
                            style={{ borderRadius: 16 }}
                            data={chartData}
                            width={screenWidth}
                            height={400}
                            chartConfig={chartConfig}
                            verticalLabelRotation={30}
                        />):null}
    

    it should make barchat load when there is data