Issue with VueJs and ChartJs not displaying custom options when making an API call

Having trouble populating my chart with data from the API. Despite setting extraOptions for my chart, it defaults to default options when rendered.

Here is the component code:

import { Bar, mixins } from 'vue-chartjs';

export default {
  name: 'bar-chart',
  extends: Bar,
  mixins: [mixins.reactiveProp],
  props: {
    extraOptions: Object,
    chartData: Object,

  },
  data() {
    return {
      ctx: null
    };
  },
  methods: {
    
  },
  mounted() {
    this.renderChart(
      this.chartData,
      this.extraOptions
    );
    this.$watch('chartData', (newVal, oldVal) => {
      if (!oldVal) {
        console.log(this.extraOptions)
        this.renderChart(
          this.chartData,
          this.extraOptions
        );
      }
    }, { immediate: true });
  }
};

My overview containing Options and API call:

  <div class="row">
        <div class="col-lg-4">
          <card>
          <bar-chart :height="heightChart" :extraOptions="optionsBar" :chart-data="BarData"> </bar-chart >
          </card>
        </div>
  </div>
</template>
<script>
  import Loading from 'src/components/Dashboard/Layout/LoadingMainPanel.vue'
  import LineChart from 'src/components/UIComponents/Charts/LineChart.vue'
  import pieca from 'src/components/UIComponents/Charts/pieca.vue'
  import Clock from './Clock.vue'
  import BarChart from 'src/components/UIComponents/Charts/BarChart'
  import axios from 'axios'


  const WorldMap = () => ({
    component: import('./../Maps/WorldMap.vue'),
    loading: Loading,
    delay: 200
  })

  export default {
    components: {
      LineChart,
      pieca,
      Clock,
      BarChart
    },
    /**
     * Chart data used to render stats, charts. Should be replaced with server data
     */
    data () {
      return {
        optionsLine: {
          ...
        },
        optionsBar: {
          ...
        },

        heightChart: 255,

        BarData: {

        },

API request:

      axios
        .get('api_url')
        .then(response => (globalthis.BarData = response.data.transporteur_jour
        ))

The issue seems to be that the chart reverts to default options after fetching data from the API. It works fine when directly feeding labels to the overview without calling the API. How can I maintain my extraOptions?

Appreciate any help!

Answer №1

Dealing with chart data in nuxt.js was a challenge I faced as well.

To solve this issue, make sure to include a key within your component. Once you receive the API response, update the value of the key. This will trigger Vue to re-render the component accordingly.

Check out my component structure:

<LineChartComponent :chart-data="datacollection" :height="400" :key="datacollection.key"></LineChartComponent>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

Encountering a problem when attempting to send a JSON object with the BeanShell PreProcessor

I need to send a JSON Object to the HTTP Request body in JMeter using the BeanShell PreProcessor. The JSON object is modeled using java code with some business logic. I have created a BeanShell PreProcessor and written the java code below, import org.json ...

How can I center a Bootstrap modal vertically and make it responsive?

Is there a way to vertically center the bootstrap modal? I have been searching for a solution, but none seem to be responsive or effective. My website is using Bootstrap 3. The modal does not adjust properly on smaller screens or when the browser window i ...

Using Regular Expressions in Firebase Functions to achieve a 'Clean Path' when utilizing app.use() in Express.js

Objective: I want Express to return /register when the browser URL is http://localhost:5000/register. This seemingly simple goal is proving to be a challenge with Express. Let's start by looking at my firebase.json: firebase.json: "hosting": { ...

Issues with PHP ajax causing database insertion failure

Here is the code for making an AJAX request: AJAX var date = new Date().toLocaleTimeString(); var text=this.value; var id=1; $.ajax({ type: "GET", url: "StoreMessages.php" , data: { room: id, msg:text, sendat:date } }); PHP Code if(isset($_GET['r ...

Why does the Ajax POST method convert my "+" value to a string?

I am having trouble understanding why the "+" sign is converting to a space in Ajax post requests. Can someone please explain this phenomenon? ...

Believing in false promises as true is what the statement assumes

I'm working on authentication for my app and encountered the following code: const ttt = currentUser.changedPasswordAfter(decoded.iat); console.log(ttt); if (ttt) { console.log('if thinks ttt is true'); The changedPasswordAfter fu ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...

Unable to bring in the Firebase Firestore Colletion

When working on my next app, I encountered an error while trying to call a Firestore Collection. The specific error message that appeared when I ran the app was: FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicat ...

Deciphering the Syntax of React Functional Components

Seeking guidance as a ReactJS novice working through the react docs. I've hit a snag trying to understand and implement an example provided in the documentation. Can anyone please lend a hand in helping me spot my mistake?https://i.sstatic.net/DwlXp.p ...

Is there a way to have text appear in a popup when I reach it while scrolling?

Is there a way to make the textblocks on my website increase in size or pop up when I scroll down to them? I've attempted to search for a solution online but have been unsuccessful in finding one. ...

Customizing the placeholder font size in Material UI Autocomplete using ReactJS

Is there a way to change the placeholder font size for Material UI Autocomplete? https://i.stack.imgur.com/x71k2.png <Autocomplete multiple id="tags-outlined" options={top100F ...

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

How can I convert a PHP date to a JavaScript date that works across all

I am attempting to create a JavaScript countdown timer that relies on the server time, but I'm facing difficulties in transferring PHP time to JavaScript seamlessly across different browsers. While it functions correctly in modern browsers, older ones ...

contrasts in regex special characters: .net versus javascript

Here is my current javascript implementation: EscapeForRegex = function(input) { var specials = ["[", "\\", "^", "$", ".", "|", "?", "*", "+", "(", ")", "{", "}"] for (var k in specials) { var special = specials[k]; ...

Incorporating a background image into a card component using props

I attempted to add a background image to the card component through props, but the image failed to display on the card. I didn't encounter any errors, and I'm unsure what mistake I might be making. Any suggestions or alternative solutions would b ...

Global variables in AngularJS that are asynchronous

My challenge lies in using AngularJS to create several global objects accessible by any controller within the application. One crucial object I require is a user object containing the user's ID and other essential properties retrieved from the databa ...

Creating a tree structure from an array in JavaScript, including the parent id enclosed in brackets

Before dismissing this question as a duplicate, please listen to me. I am working with a json response in reactjs that looks like the following organisationUnits: [ { name: "0.Mzondo", id: "nW4j6JDVFGn", parent: { ...

How do the JavaScript thread and the Silverlight UI thread interact with each other?

While JavaScript operates on a single thread, Silverlight does not follow the same restrictions. However, when it comes to the interaction between JavaScript and Silverlight, it is crucial that communication occurs on the Silverlight UI thread. The relati ...