Search code examples
javascriptreactjsmui-datatable

Adding the 2nd timestamp shows this error failed to fetch data TypeError: Cannot read properties of undefined (reading 'seconds')


If I add the editedAt, it will throw this error:

failed to fetch data TypeError: Cannot read properties of undefined (reading 'seconds')

however, if I remove the data where it has the timestamp value of editedAt from the database. This will not cause an error. Is this because not all of the data have timestamp value of editedAt?

How do I fix this error since I need to display the data with the editedAt as well?

And this is the data:

const data = [
  {
    createdDate: { seconds: 1647660530, nanoseconds: 228000000 },
    id: "4jnEbtIGLKTgEnJYX7ci"
  },
  {
    editedAt: { seconds: 1647665687, nanoseconds: 627000000 },
    id: "vBBeIQsNbqvbqVWNIK6k"
  },
  {
    createdDate: { seconds: 1646370332, nanoseconds: 678000000 },
    id: "Hs29gnvfeD0cSQkNmsRn"
  },
  {
    createdDate: { seconds: 1645840425, nanoseconds: 486000000 },
    id: "gagdiaihdihaihsd"
  }
];

These are the codes:

 const columns = [
    {
      name: "createdDate",
      label: "Date",
      options: {
        filter: true,
        sort: true,
        customBodyRender: (value, tableMeta, updateValue) => {
          return new Date(value.seconds * 1000).toLocaleDateString();
        },
      },
    },
    {
      name: "editedAt",
      label: "Edited Date",
      options: {
        filter: true,
        sort: true,
        customBodyRender: (value, tableMeta, updateValue) => {
          return new Date(value.seconds * 1000)?.toLocaleDateString();
        },
      },
    },
  ];

Solution

  • Each item in your data array should have the fields "createdDate" and "editedAt".

    If you wish to not do that, use the optional ? operator to handle no data or check for value:

    if (value) { ... do render } else { ... do something else }

    value?.seconds could return undefined or access the seconds property.