Caleb
Caleb

Reputation: 489

Chart js in React/Gatsby

Hello I am trying to use chart js in Gatsby. I am currently following a tutorial for using chart js with react and I am not sure if the issue is that he is using creat-react-app and not Gatsby, but the errors do not seem to indicate that.

first I installed the following:

npm i --save react-chartjs-2

then

npm i --save chart.js

chartData.js:

import React, {useState, useEffect } from "react";
import { Line } from "react-chartjs-2";


const chartData = () => {
    const [chartData, setChartData] = useState({});

    const chart = () => {
        setChartData({
            labels: ["monday", "tuesday", "wednesday", "thursday", "friday"],
            datasets: [
                {
                    level: 'level of xyz',
                    data: [32, 55, 33, 47, 64]
                }
            ]
        })
    }

    useEffect(() => {
        chart()
    }, [])
    return(
        <div>
            <h1>Hello</h1>
            <div>
                <Line data={chartData}/>
            </div>
        </div>
    )
}

export default chartData;

I am getting these erros:

   6:39  error  React Hook "useState" is called in function "chartData" which is neither a React function component or a custom React Hook function   react-hooks/rules-of-hooks
  20:5   error  React Hook "useEffect" is called in function "chartData" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

Upvotes: 0

Views: 1007

Answers (2)

andrewkepson
andrewkepson

Reputation: 9

You need to capitalize the name of the component. Right now you are setting the component to chartData, and then defining chartData as a hook. Change the component to ChartData.js

Upvotes: 0

Ferran Buireu
Ferran Buireu

Reputation: 29320

You have a name cohersion issue. Try renaming the functions and variables with a diferent name:

import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";


const ChartData = () => {
    const [whatever, setWhatever] = useState({});

    const chart = () => {
        setWhatever({
            labels: ["monday", "tuesday", "wednesday", "thursday", "friday"],
            datasets: [
                {
                    level: 'level of xyz',
                    data: [32, 55, 33, 47, 64]
                }
            ]
        })
    }

    useEffect(() => {
        chart()
    }, [])

    return(
        <div>
            <h1>Hello</h1>
            <div>
                <Line data={whatever}/>
            </div>
        </div>
    )
}

export default ChartData;

In your previous code:

const chartData = () => {
    const [chartData, setChartData] = useState({});
...
}

Where chartData is duplicated causing the error.

In addition, your chartData must be ChartData since, in React, the components must be capitalized.

Upvotes: 1

Related Questions