0

I'm trying to generate a bar chart using chartjs with the useEffect i'm calling the generateChart method setting the new chart object in chartS variable. but in the initial load if I clicked on a bar, the filterChart method gets called in the onClick function only has the initial null value but not the chart object

const dispatch = useDispatch();
const filters = useSelector((state) => {
    return state.filters;
});
const generateChart = () => {
    getData().then((data) => {
        if (chartS) {
            chartS.destroy();
        }
        setChartS(new ChartJS(document.getElementById("chart"), {
            type: "bar",
            options: {
                responsive: true,
                onClick: (e, legendItem) => {
                    if (legendItem[0]) {
                        filterCharts(e.chart, legendItem[0].element.$context.dataIndex);
                    }
                }
            },
            data: chartJsData(data)
        }));
    });
}


useEffect(() => {
    generateChart();
}, [filters]);

above is the generate method calling the filterChart from the onClick. The filterChart function is as follows,

const [chartS, setChartS] = useState(null);

const filterCharts = (chartObj, index) => {
    console.log("chartS", chartS); /// this is still null though we set that using setChartS in getData function
    if (chartObj?.data?.labels[index]) {
        if (filters && filters.years && filters?.years?.includes(chartObj?.data?.labels[index]) && filters.years.length === 1) {
            return;
        }
        dispatch({
            type: "removeAllAddYear",
            payload: chartObj.data.labels[index]
        });

    }
}

Why do I receive a null value instead of the new chart object which was updated in the generateChart function?

RoHaN
  • 1,356
  • 2
  • 11
  • 21
  • 1
    Because useState is a stale state and you can't reference to the latest value inside your callback for some cases. Have you consider to use useRef instead @RoHaN. – Toan Quoc Ho Mar 23 '22 at 18:44
  • And make sure this element is in the document, it's better to use a ref here to refer to an element. – Toan Quoc Ho Mar 23 '22 at 18:46
  • it worked after I changed it to a useRef as you mentioned. Thanks for your help! – RoHaN Mar 23 '22 at 18:56

0 Answers0