Home > database >  2022 React - Expected an assignment or function call and instead saw an expression
2022 React - Expected an assignment or function call and instead saw an expression

Time:03-27

I am trying to update a chart with the values I get from the API. I don't know how to tweak this useEffect hook. If you could advise, I would owe you a lot.

Let me show my code:

import React, { useEffect, useState } from "react";
import { useQuery, gql } from "@apollo/client";
import { Bar } from "react-chartjs-2";

const total = gql`
query GetIntell {
  webs(
    sort: "severity:desc",
    pagination: { start: 0, limit: 10 },
    filters: {site  :{eq: "nist"}}
  ) {
    data {
      id
      attributes {
        dateAdded
        severity

      }
    }
  }
}
`

export default function Test() {

  const {data }= useQuery(total)
  const [chartData, setChartData] = useState({})
  useEffect (() => {.  <--------HERE COMES THE ERROR Line 29:5: 
    setChartData({
      labels: data.webs.data.map((t) => t.attributes.severity),
      datasets: [
        {
          label: "Price in USD",
          data: data.webs.data.map((t) => t.attributes.id),
          backgroundColor: [
            "#ffbb11",
            "#ecf0f1",
            "#50AF95",
            "#f3ba2f",
            "#2a71d0"
          ]
        }
      ]
    }), [data]

  })
  
  console.log(data)

  return (
    <div className="container">
      <Bar
        data={chartData}
        options={{
          plugins: {
            title: {
              display: true,
              text: "Cryptocurrency prices"
            },
            legend: {
              display: true,
              position: "bottom"
           }
          }
        }}
      />
    </div>
  );
}

Basically I need to get the graph data, only after the const data is retrieved from graphql. I have no clue how to tweak the code to run it ok.

I've seen a lot of old code with this error so I could not find a newer topic with this error to check it.

Later Edit This is how the data looks like data json

CodePudding user response:

Your useEffect dependency array is in the wrong place, I think that's what is causing it.

should be:

useEffect (() => {
    setChartData({
      labels: data.webs.data.map((t) => t.attributes.severity),
      datasets: [
        {
          label: "Price in USD",
          data: data.webs.data.map((t) => t.attributes.id),
          backgroundColor: [
            "#ffbb11",
            "#ecf0f1",
            "#50AF95",
            "#f3ba2f",
            "#2a71d0"
          ]
        }
      ]
    })
  }, [data])

Also ther is a . on the line you have the arrow on but I'm not sure id it's a copy paste typo or is it actually in your code

  • Related