Search code examples
modulenuxt.jsnuxt3.jsechartsdynamic-data

How to update series data correctly in Nuxt eCharts module?


I'm using Nuxt eCharts 0.2.4 and am having trouble updating the series data after fetching new data. I'm able to add the new data series, but an old series still lingers and never goes away no matter how many new data fetches I do.

My strategy so far has been to clear out the chart configuration ref (option.value.series) when I fetch new data, like:

// other code

const option = ref({
  series: [{ type: 'bar' }],
})

// other code

// fetch data
option.value.series = []
// do some data wrangling
option.value.series.push(newData)

What results is the new data series appear correctly, but one of the first data series remains and never goes away.

I see that there's a setOption ref in the Nuxt eCharts docs that I want to try to use but I don't know how.


Solution

  • I suspect this happens because options are merged by default which results in series remaining unchanged, if they are not specified in the new option.

    The Nuxt ECharts documentation states

    option: ECharts' universal interface. Modifying this prop will trigger ECharts' setOption method.

    and

    When update-options is not specified, notMerge: false will be specified by default when the setOption method is called .

    Thus, when option.value.series = [] is extecuted, it is merged with the previous option. As a result the new option is equivalent to the previous one. After that you just add another series.

    To solve your issue you need to pass update-options to your chart. The update-option you are looking for is probably replaceMerge. From echarts documentation:

    Replace Merge: Within a specific component main type (e.g., xAxis, series), only the existing components that has its id declared in the incoming option will be kept, other existing components will be removed or replaced with new created component.

    As stated above I would advice to specify a series id for each series. Your final chart element should look something like this:

    <script>
      const option = ref({
        series: [{ id: '1', type: 'bar'}]
      });
      const update-options = { replaceMerge: ['series'] };
    
      // other code
    
      // fetch data
      option.value.series = [{ id: '1', data: newData}];
    </script>
    
    
    <template>
      <VChart
        :option="option"
        update-options="update-options"
      />
    </template>