简体   繁体   中英

Memory leak error while showing chartjs 2 graph

import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from "chart.js"
import { Bar } from "react-chartjs-2"

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)

function Reports() {
  const [graph, setGraph] = useState({})

  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: "top",
      },
      title: {
        display: true,
        text: "Chart.js Bar Chart",
      },
    },
  }

  const handleAllLeadsGenerated = () => {
    axios({
      method: "get",
      url: `${serverUrl}/reports/leads`,
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
      .then((res) => {
        console.log("response: ", res)
        setGraph({
          labels: res.data.map((row) => {
            return row.firstname
          }),
          datasets: [
            {
              label: "Leads Generation",
              data: res.data.map((row, index) => {
                return parseInt(row.countn)
              }),
              backgroundColor: "rgba(255, 99, 132, 0.5)",
            },
          ],
        })
      })
      .catch((err) => {
        console.log("error: ", err)
      })
  }

  useEffect(() => {
    handleAllLeadsGenerated()
    // eslint-disable-next-line
  }, [])

  return (
    <>
      <div className="content">
        <ToastContainer position="top-right" autoClose={5000} hideProgressBar={false} newestOnTop closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover theme="colored" />
        <Tabs>
          <TabList>
            <Tab>Leads Generation</Tab>
            <Tab>Recuiters Report</Tab>
          </TabList>
          <TabPanel>
            <Row>
              <Col md="12">
                <Card>
                  <CardHeader style={{ display: "flex", alignItems: "center" }}>
                    <CardTitle tag="h4">Leads Info</CardTitle>
                    <Button onClick={handleAllLeadsGenerated}>Reload</Button>
                  </CardHeader>
                  <CardBody>{graph ? <Bar options={options} data={graph} /> : <Spinner animation="border" />}</CardBody>
                </Card>
              </Col>
            </Row>
          </TabPanel>
        </Tabs>
      </div>
    </>
  )
}

export default Reports

I am trying to show a graph of no. of leads generated by a user. when I go this component its shows memory leak error(blank page, nothing renders). But if I comment the <Bar /> component in the CardBody, and then uncomment it, it shows the graph while reloading the page, or coming from another page gives the error.

First time loading the component or reloading the page: 第一次加载组件或重新加载页面

Commenting and uncommenting the Bar component line, after compiling the code again it shows the graph: 在此处输入图像描述

Your ternary

{graph ? <Bar options={options} data={graph} /> : <Spinner animation="border" />}

is always true since empty object is truthy, so it will try to render the Bar component without the data ready I suppose.

Try

{graph.length > 0 ? <Bar options={options} data={graph} /> : <Spinner animation="border" />}
{Object.keys(graph).length > 0 ? <Bar options={options} data={graph} /> : <Spinner animation="border" />}

This solved my issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM