Chartjs-Chart.js random weird problems

0👍

Your code works fine on the first render for me. I am not 100% sure from your description what you think is going wrong, but 1 problem I see is that useEffect will only run once due to the [] in the second parameter.

If your prop.score updates, useEffect() won’t run again, which means your chart won’t update.

The main change I did below was add props.score in the array for useEffect, this tells useEffect to run again if props.score changes. You can read more about this in the useEffect docs

import React, { useEffect } from 'react'
import Chart from 'chart.js';

const LineChart = (props) => {
    const number = props.score //***i am trying to get props.score into the chart js data point. 

    console.log(number) //****this console logs 82

    const newNumber = 10 + number
    console.log(newNumber) //***this console logs 92

    useEffect(() => {
        var ctx = document.getElementById('myLineChart');

        var myChart = new Chart(ctx, {
            type: 'line',
            responsive: true,
            data: {
                labels: ['X', 'IQ', 'X'],
                datasets: [{
                    label: 'Your Score',
                    data: [0, newNumber, 0],
                    backgroundColor: [
                        'rgba(54, 80, 235, 0.2)',
                        'rgba(54, 80, 235, 0.2)',
                        'rgba(54, 162, 235, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                    ],
                    borderWidth: 1,

                },
                {
                    label: 'Average',
                    data: [0, 100, 0],
                    backgroundColor: [
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(54, 80, 235, 0.2)',
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, .5)',
                        'rgba(255, 99, 132, .5)',
                        'rgba(255, 99, 132, .5)',
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: false,
                            suggestedMin: 70,
                            suggestedMax: 160,
                            stepSize: 10
                        }

                    }]
                }
            }
        });
    }, [props.score])
    return (
        <div >
            <canvas id="myLineChart" width="650" height="400"></canvas>
        </div>
    )
}

export default LineChart

Leave a comment