Chrome console displaying error in vanilla JavaScript: 'Unable to set property of undefined'

Hello, I am a newcomer to chartjs and JavaScript in general. I keep encountering the error "cannot set property of undefined" in the Chrome console.

const dataPie = {

    labels: ['Good Packs', 'Bad Packs'],
    datasets: [{
        label: 'My First Dataset',
        data: [0.1, 0.1],
        backgroundColor: ['#00bf90', 'rgb(255, 75, 75)'],
        hoverOffset: 0
    }]
};

const configPie = {
    type: 'pie',
    data: dataPie,
    options: {}
};

const pieChart = new Chart(
    document.getElementById('chart-pie'),
    configPie
);

Then, in a timed loop, I am trying to perform the following operation and encountering the error "cannot set property of undefined" (I am not setting the value in HTML, it is only set when building the pie chart at the top).

pieChart.data.datasets.data[0] = 0.5;

Since I am new to JavaScript, any help would be greatly appreciated!

Answer №1

It seems like the data was being accessed incorrectly. I will provide a link to the documentation for reference. I have made some changes to your code snippet below (no timer, but the code will update). Remember to call the update function after changing the value to update the HTML.

The datasets variable is an array, so you need to specify the index of the dataset you want to modify. In this case, it is [0] since there is only one dataset present.

Check out the ChartJs Documentation here: https://www.chartjs.org/docs/latest/developers/api.html

const dataPie = {

    labels: ['Good Items', 'Bad Items'],
    datasets: [{
        label: 'First Data Set',
        data: [0.2, 0.2],
        backgroundColor: ['#ffcc00', 'rgb(65, 105, 225)'],
        hoverOffset: 0
    }]
};

const configPie = {
    type: 'pie',
    data: dataPie,
    options: {}
};

const pieChart = new Chart(
    document.getElementById('chart-pie').getContext('2d'),
    configPie
);

pieChart.data.datasets[0].data[0] = 0.8;
pieChart.update('active');
<script src="https://cdn.example.com/dist/chart.min.js"></script>
<canvas id="chart-pie" width="400" height="400"></canvas>

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

Implementing a PHP back button to navigate through previous pages

Currently, I am in the process of coding a project. In this project, there are a total of 10 pages, each equipped with back and forward buttons. However, when I attempt to navigate using either javascript:history.go(-1) or $url = htmlspecialchars($_SERVER ...

Analyzing random sequences of bits within a byte array using c

In my C code, I am working with a couple of uint8_t arrays and need to compare specific sequences of bits between them. For instance, I have bitarray_1 and bitarray_2, and I want to compare bits 13-47 from bitarray_1 with bits 5-39 from bitarray_2. What is ...

Creating multiple React applications using shared configuration files: A step-by-step guide

I am in the process of developing a React app, and my goal is to create multiple React apps that share the same configurations - including modules and configuration files like tailwind.config.cjs. How can I modify my environment to achieve this? My plan i ...

Angular8: Adjusting Activity Status After Leaving Page

When performing activities like upload, download, delete, and edit, I display statuses such as 'upload started' or 'upload completed'. This works perfectly when staying on the same page. However, there are instances where a user may nav ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. https://i.sstatic.net/EyTZE.jpg My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...

A guide to incorporating border radius to images within a composite image with sharp.js in Node.js

In my Node.js project, I am using the sharp library to combine a collection of images into a single image. Although I have successfully created the composite image, I now need to add a border radius to each of the images in the grid. Here is the code snip ...

Trouble with Directive - the watch function isn't functioning as expected

After spending countless hours and trying almost everything, I can't seem to get it to work... I have an Angular directive that calls another Angular directive. I need to handle events in the child directive. So my child directive looks like: ...

Inserting Random Data into MySQL Tables using Node.js

I am currently working on developing a game bot for Discord similar to Town of Salem, Wolvesville, Feign, and others. Within my database, I have a table called "joinedplayer" which stores users who have used the "join" command: gamerid discordid 1 ...

The functionality of displaying an animated gif will not work when submitting a CakePHP ajax form before or after completion

I have exhaustively tested all possible scenarios using prototype, but I am unable to get my busy indicator to show no matter what I do. Despite cross-browser testing, I've had no luck. <?php echo $ajax->submit('Submit', array(' ...

Is there a way to directly update the value of a nested object array using v-model in VUE?

Looking to update a value in JSON using v-model { class: "data.child", "myform.input1": [true, "<input1 value>"] } <input type="text" v-model="<what should be inserted here?>" > //update the value directly in my ...

The largest allowable call stack size within jQuery version 1.9.0

I have a question about poorly written code that I've been experimenting with. It's messy, but it's just for fun. I was attempting to create a "like system" where a user clicks on a button and the object ID associated with the button is sent ...

Having issues with setting state for an array in ReactJS

I am currently working on a component called Inbox which includes a checkbox feature. However, I am facing an issue where the checkbox only works on the third click and fails to respond on the first and second clicks. The setState function seems to be wo ...

JQuery/JS function not functioning as expected

Creating HTML with jQuery to retrieve data from a web API. At the start of my script, I defined a function that checks the selected value of a dropdown and assigns it to a global variable. var $seldom; $(document).ready(function () { function chkdom() ...

Create directories in a nested structure using a multi-level JSON object with async.js

DEFINITION NewMethod#generateDirectoriesFromJSON (data, cb); data: JSON object. cb: Callback function. Parameters: err (Error), directoriesCreated (Boolean, true if at least one directory has been created). Assuming that the NewMethod class includes a ...

Why do all the cards suddenly come to life when I press the activate button on just one card?

Whenever I try to activate a specific card by clicking the active button, all the cards end up getting activated. I have used the className variable and manually set it to "card mb-3 border-3". My intention is for the className to change when clicking th ...

Having trouble persisting and displaying information in MongoDB with Mongoose

app.post('/contact', (req, res)=> { var myData = new Contact(req.body); myData.save().then(()=>{ res.send("Item has been saved"); }).catch(()=>{ res.send('Item was not saved due to some error'); ...

What's the Purpose of Using an Arrow Function Instead of Directly Returning a Value in a React Event Handler?

After skimming through various textbooks and blog posts, I've noticed that many explanations on event handlers in React are quite vague... For example, when instructed to write, onChange = {() => setValue(someValue)} onChange = {() => this.pro ...

Experiencing a problem with a loop structure in my code

I've been trying to create a loop that will increase the temperature by 10 degrees every 2 minutes. However, I'm struggling to figure out how to stop the temperature at 120 degrees after 16 minutes. Any suggestions on how to solve this issue? va ...

Performing calculations in Javascript using input and span elements

<input type="number" name="quantity" id="quantity"> <span id="price">4000</span> <input type="text" value="" id="total" readonly> <input type="button" value="calculate Total Price" onClick="calculate()"> I have a form with f ...

Utilizing Vue refs to set focus on a specific element target

Clicking on "span class="before-click" should hide it, and display input class="after-click" instead. The displayed input must be in focus! However, when trying to use $refs.afterClick to access the DOM and apply .focus(), an unexpected error stati ...