Updating chart with data from Firestore realtime listener

Viewed 37

In my Vue app I am using Apexcharts to display some data. I am grabbing the data from my Firestore database by using a realtime listener.

The chart is working as it should and I am also getting the data in realtime. The problem is that my chart is not updating itself with the new data, and I am not sure on how to approach it.

I am fetching the data my parent component through this script:

onMounted(async () => {
      const unsub = onSnapshot(doc(db, "testUsers", "rtBp8UHReBE2rACDBHij"), (doc) => {
        getWeight.value = doc.data();
      });
      watchEffect((onInvalidate) => {
        onInvalidate(() => unsub());
      });
    });

I am sending the data to my child component through props like this:

watch(
      () => props.getWeight,
      (getWeights) => {
        weight.value = [...getWeights.weightData.weight];

        let numeric = { day: "numeric", month: "numeric" };

        getWeights.weightData.date.forEach((dates) => {
          date.value.push([dates.toDate().toLocaleDateString("se-SW", numeric)]);
        }),
      }
    );

My chart in the child component looks something like this:

  <apexchart class="apexchart" type="line" :options="options" :series="series">
  </apexchart>

<script>
export default {
  props: ["weight", "date"],

  setup(props) {
    return {
      options: {

        xaxis: {
          type: "category",
          categories: props.date,

          axisBorder: {
            show: false,
          },
        },
      },
      series: [
        {
          name: "Værdi",
          data: props.weight,
        },
      ],
    };
  },
};
</script>

How can I make my chart update with the new data from the realtime listener?

1 Answers

If in chart options you add id you would be able to call exec and update your chart

Example:

import ApexCharts from "apexcharts";

ApexCharts.exec('chartId', 'updateOptions', {
  series: [
    {
      name: 'Værdi',
      data: newWeights,
    },
  ],
  xaxis: {
    categories: newDates,
  },
})
Related