最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React UseTable: TypeError: Cannot read properties of undefined (reading 'forEach') - Stack Overflow

programmeradmin2浏览0评论

Quick help here! I got the above error when i try to render data into react table. The data come from an api via axios.

Here is the code

import axios from "axios";
import React, { useEffect, useState, useMemo } from "react";
import "./Modal.css";
import { useTable } from "react-table";
import { COLUMNS } from "./columns";
import "./my_style.css";
const ViewTcMapping = () => {
  const [data, setData] = useState({});

  const baseURL =
    "http://127.0.0.1:8000/api/business_process/risk_tc_mapping_details";

  useEffect(() => {
    axios
      .get(baseURL)
      .then((response) => {
        setData(response.data);
      })
      .then(
        (response) => {},
        (err) => {
          alert("No Data To Show");
        }
      )
      .catch((err) => {
        return false;
      });
  }, []);

  const columns = useMemo(() => COLUMNS, []);
  const mydata = useMemo(() => data, []);
  const tableInstance = useTable({
    columns,
    mydata,
  });

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = tableInstance;
  return (
    <div className="z-100 flex justify-center items-center">
      <div className="text-black">
        <div className="rounded overflow-hidden flex  justify-center items-center">
          <table {...getTableProps()} class="GeneratedTable">
            <thead>
              {headerGroups.map((headerGroup) => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                  {headerGroup.headers.map((column) => (
                    <th {...column.getHeaderGroupProps()}>
                      {column.render("Header")}
                    </th>
                  ))}
                </tr>
              ))}
            </thead>

            <tbody {...getTableBodyProps()}>
              {rows.map((row) => {
                prepareRow(row);
                return (
                  <tr {...row.getRowProps}>
                    {row.cells.map((cell) => {
                      return (
                        <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default ViewTcMapping;

Here is COLUMNS which contains the heading of each column

export const COLUMNS = [
  {
    Header: "Cost",
    accessor: "cost_category",
  },
  {
    Header: "Path",
    accessor: "path",
  },
  {
    Header: "Threat Category (PK)",
    accessor: "threat_category",
  },
  {
    Header: "Threats (ISO)",
    accessor: "threats",
  },
  {
    Header: "Asset Type",
    accessor: "asset_type",
  },
  {
    Header: "Comment",
    accessor: "comment",
  },
  {
    Header: "Operational",
    accessor: "operational",
  },
  {
    Header: "Reputational",
    accessor: "reputational",
  },
  {
    Header: "Financial",
    accessor: "financial",
  },
  {
    Header: "Health and Safety",
    accessor: "health_and_safety",
  },
  {
    Header: "Environmental",
    accessor: "environment",
  },
];

Here is the api json data I wanted to render to the table

{
    "tc_mapping_details": [
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "Phishing",
            "threats": "Social engineering",
            "asset_type": "User",
            "comment": "Phishing by itself may not cause a breach, unless it is in combination with middle and end activities. Loss event (Breach) is calculated per exposed path that leads to the end action. For the rest, loss can be treated merely as an incident",
            "operational": "I",
            "reputational": null,
            "financial": null,
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Ransom-ware",
            "threats": "Malicious code",
            "asset_type": "Email Properties",
            "comment": "Ransomware can't launch on it own. It needs an Entry point. It needs an End point for Extortion or Breach (For example, Data Tampering or Data Compromise resp,)..",
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Malicious Software (Malware, Virus etc.)",
            "threats": "Malicious code",
            "asset_type": "Server, Network",
            "comment": "Ransomware can't launch on it own. It needs an Entry point. It needs an End point for an Attack or Breach (For example, Data Tampering or Data Compromise resp,)..",
            "operational": "I",
            "reputational": null,
            "financial": null,
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Espionage",
            "threats": "Software espionage",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": null,
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Espionage",
            "threats": "Industrial espionage",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": "I",
            "environment": "I"
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "Web Vulnerabilities",
            "threats": "Vulnerability",
            "asset_type": "Web Properties",
            "comment": null,
            "operational": "I",
            "reputational": null,
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "3rd Party Vulnerabilities (inc. Software)",
            "threats": "Vulnerability",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "End",
            "threat_category": "Fraud",
            "threats": "Fraud",
            "asset_type": null,
            "comment": null,
            "operational": "B",
            "reputational": "B",
            "financial": "B",
            "health_and_safety": null,
            "environment": null
        },
       
    ]
}

How can I fix TypeError: Cannot read properties of undefined (reading 'forEach') ?

Thanks

Quick help here! I got the above error when i try to render data into react table. The data come from an api via axios.

Here is the code

import axios from "axios";
import React, { useEffect, useState, useMemo } from "react";
import "./Modal.css";
import { useTable } from "react-table";
import { COLUMNS } from "./columns";
import "./my_style.css";
const ViewTcMapping = () => {
  const [data, setData] = useState({});

  const baseURL =
    "http://127.0.0.1:8000/api/business_process/risk_tc_mapping_details";

  useEffect(() => {
    axios
      .get(baseURL)
      .then((response) => {
        setData(response.data);
      })
      .then(
        (response) => {},
        (err) => {
          alert("No Data To Show");
        }
      )
      .catch((err) => {
        return false;
      });
  }, []);

  const columns = useMemo(() => COLUMNS, []);
  const mydata = useMemo(() => data, []);
  const tableInstance = useTable({
    columns,
    mydata,
  });

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = tableInstance;
  return (
    <div className="z-100 flex justify-center items-center">
      <div className="text-black">
        <div className="rounded overflow-hidden flex  justify-center items-center">
          <table {...getTableProps()} class="GeneratedTable">
            <thead>
              {headerGroups.map((headerGroup) => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                  {headerGroup.headers.map((column) => (
                    <th {...column.getHeaderGroupProps()}>
                      {column.render("Header")}
                    </th>
                  ))}
                </tr>
              ))}
            </thead>

            <tbody {...getTableBodyProps()}>
              {rows.map((row) => {
                prepareRow(row);
                return (
                  <tr {...row.getRowProps}>
                    {row.cells.map((cell) => {
                      return (
                        <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default ViewTcMapping;

Here is COLUMNS which contains the heading of each column

export const COLUMNS = [
  {
    Header: "Cost",
    accessor: "cost_category",
  },
  {
    Header: "Path",
    accessor: "path",
  },
  {
    Header: "Threat Category (PK)",
    accessor: "threat_category",
  },
  {
    Header: "Threats (ISO)",
    accessor: "threats",
  },
  {
    Header: "Asset Type",
    accessor: "asset_type",
  },
  {
    Header: "Comment",
    accessor: "comment",
  },
  {
    Header: "Operational",
    accessor: "operational",
  },
  {
    Header: "Reputational",
    accessor: "reputational",
  },
  {
    Header: "Financial",
    accessor: "financial",
  },
  {
    Header: "Health and Safety",
    accessor: "health_and_safety",
  },
  {
    Header: "Environmental",
    accessor: "environment",
  },
];

Here is the api json data I wanted to render to the table

{
    "tc_mapping_details": [
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "Phishing",
            "threats": "Social engineering",
            "asset_type": "User",
            "comment": "Phishing by itself may not cause a breach, unless it is in combination with middle and end activities. Loss event (Breach) is calculated per exposed path that leads to the end action. For the rest, loss can be treated merely as an incident",
            "operational": "I",
            "reputational": null,
            "financial": null,
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Ransom-ware",
            "threats": "Malicious code",
            "asset_type": "Email Properties",
            "comment": "Ransomware can't launch on it own. It needs an Entry point. It needs an End point for Extortion or Breach (For example, Data Tampering or Data Compromise resp,)..",
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Malicious Software (Malware, Virus etc.)",
            "threats": "Malicious code",
            "asset_type": "Server, Network",
            "comment": "Ransomware can't launch on it own. It needs an Entry point. It needs an End point for an Attack or Breach (For example, Data Tampering or Data Compromise resp,)..",
            "operational": "I",
            "reputational": null,
            "financial": null,
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Espionage",
            "threats": "Software espionage",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": null,
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Espionage",
            "threats": "Industrial espionage",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": "I",
            "environment": "I"
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "Web Vulnerabilities",
            "threats": "Vulnerability",
            "asset_type": "Web Properties",
            "comment": null,
            "operational": "I",
            "reputational": null,
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "3rd Party Vulnerabilities (inc. Software)",
            "threats": "Vulnerability",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "End",
            "threat_category": "Fraud",
            "threats": "Fraud",
            "asset_type": null,
            "comment": null,
            "operational": "B",
            "reputational": "B",
            "financial": "B",
            "health_and_safety": null,
            "environment": null
        },
       
    ]
}

How can I fix TypeError: Cannot read properties of undefined (reading 'forEach') ?

Thanks

Share Improve this question edited Jan 14, 2022 at 17:15 Teshie Ethiopia asked Jan 14, 2022 at 16:57 Teshie EthiopiaTeshie Ethiopia 6662 gold badges15 silver badges34 bronze badges 1
  • 1 Your code doesn't have a forEach in itself, so the error comes from somewhere in the libraries you're using. You will need to show more of the error stack, not just the error. – AKX Commented Jan 14, 2022 at 17:07
Add a comment  | 

4 Answers 4

Reset to default 14

I found solution for you. I just encountered the same problems.

In the useTable hooks, you have to pass useTable({ columns, data: 'yourData' }) since the accessRows forEach is for keyword data.

Try it as following:

const ViewTcMapping = () => {
  const [data, setData] = useState([]);
  ...
}

ReactTable requires array data, but initial data type of data is object, so forEach is not valid.

Maybe the first render isn't getting the values. You can try to use the conditional chaining '?' after your object. Like rows?.map((row)

while passing the data props to the table you can pass like below by giving empty array which helps you when your array becomes undefined or null,`<Table data={this.props.studentList || []}]/>

<Table data={this.props.studentList || []} />

In this code, if this.props.studentList is undefined or null, it will default to an empty array, which is a safe and common way to handle such situations. This helps prevent errors when the data is missing or not yet available.

发布评论

评论列表(0)

  1. 暂无评论