Gird component ID error

Cannot read properties of null (reading 'id') TypeError: Cannot read properties of null (reading 'id') at NormalEdit.clickHandler (http://localhost:3000/static/js/bundle.js:96998:338) at Observer.notify (http://localhost:3000/static/js/bundle.js:28256:21) at Component.notify (http://localhost:3000/static/js/bundle.js:21704:26) at Grid.mou

import React, { useEffect, useState, useRef } from 'react';
import { GridComponent, ColumnsDirective, ColumnDirective, Page, Selection, Inject, Edit, Toolbar, Sort, Filter, Search, Group, PdfExport, CommandColumn } from '@syncfusion/ej2-react-grids';
import { L10n } from '@syncfusion/ej2-base';
import { Header, Loader } from '../components';
import useAxios from '../utils/useAxios';
import { hermanosTabla } from '../data/info';
import { useNavigate } from 'react-router-dom';

const Hermanos = () => {
  const [dataLoaded, setDataLoaded] = useState(false);
  const selectionsettings = { persistSelection: true };
  const toolbarOptions = [{ text: 'Eliminar', id: 'Grid_delete', prefixIcon: 'e-delete' }, 'Buscar'];
  const sortSettings = {
    columns: [
      { field: 'name', direction: 'Ascending' }
    ]
  };
  const editing = { allowDeleting: true, allowEditing: false };
  const [data, setData] = useState([]);
  const api = useAxios();
  const navigate = useNavigate();
  const gridRef = useRef(null);

  const fetchData = async () => {
    try {
      const response = await api.get('/db/hermanos');
      setData(response.data.data);
      setDataLoaded(true);
    } catch (error) {
      console.error('Error fetching data', error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const clickHandler = async (args) => {
    if (args.item.id === 'Grid_delete' && gridRef.current) {
      const selectedRecords = gridRef.current.getSelectedRecords();

      for (const user of selectedRecords) {
        await api.delete(`/db/hermanos/${user.id}`);
      }

      fetchData();
    }
  };

  const commandClickHandler = (args) => {

    const record = args.rowData;
    if (args.commandColumn.buttonOption.content === 'Editar') {
      console.log(record.id)
      if (record && record.id) {
        console.log(record)
        navigate(`/panel/editar-hermano/${record.id}`);

      } else {
        console.error('El registro no es válido', record);
      }
    }
  };



  if (!dataLoaded) return (<Loader />);


  return (
    <div className="m-2 md:m-10 mt-24 p-2 md:p-10 bg-white rounded-3xl">
      <Header category="Gestión" title="Hermanos" />
      <GridComponent
        id="Grid"
        dataSource={data}
        width="auto"
        allowPaging
        selectionSettings={selectionsettings}
        pageSettings={{ pageCount: 12 }}
        editSettings={editing}
        toolbar={toolbarOptions}
        toolbarClick={clickHandler}
        ref={gridRef}
        allowSorting={true}
        sortSettings={sortSettings}
        allowFiltering={true}
        allowGrouping={true}
        locale='es-ES' // Configurar localización
        commandClick={commandClickHandler}
      >
        <ColumnsDirective>
          {hermanosTabla.map((item, index) => (
            <ColumnDirective key={index} {...item} headerText={item.headerText} />
          ))}
          <ColumnDirective headerText='Acciones' width='200' commands={[
            { buttonOption: { content: 'Editar', cssClass: 'e-flat' } },
          ]} />
        </ColumnsDirective>
        <Inject services={[Page, Selection, Toolbar, Edit, Sort, Filter, Group, PdfExport, CommandColumn]} />
      </GridComponent>
    </div>
  );
};

export default Hermanos;

seClickHandler (http://localhost:3000/static/js/bundle.js:111154:10)


7 Replies 1 reply marked as answer

SR Sivaranjani Rajasekaran Syncfusion Team July 15, 2024 02:08 PM UTC

Hi Swadowmaster,

Greetings from Syncfusion Support,

After reviewing the code snippet you provided, we found that you haven't specified the field property for the grid columns. Consequently, the grid initially displays empty records. To enable CRUD operations, the editing feature requires a primary key column. You need to define the primary key by setting isPrimaryKey to true in a specific column. Please ensure that after setting the field property, you designate a unique column of the grid as the primary key.

  1. Please share the field details of your grid column.
  2. Please provide details on the specific case where you are encountering the issue (e.g., while editing). Please include the steps to replicate the issue.
  3. In your code snippet, you logged record.id in the console, but we did not see records or record details in your code. Could you please provide details on this?
  4. Please share a reproducible sample with, include the grid configuration.

With this information, we will be better equipped to assist you


Thank you for your cooperation.

Regards,
Sivaranjani R.


S1 swadowmaster 102 July 15, 2024 02:42 PM UTC

this is my grid config and id is with isPrimaryKey , my function to delete works correctly and with edit i only need t redirect to other page with ID in uri but it give me id errors idk why because if i put id manually the error remains 
Here example of record output 
Image_7827_1721054544574

export const hermanosTabla = [
    { type: 'checkbox', width: '50' },
    {
        field: 'name',
        headerText: 'Nombre',
        width: '150',
        template: customerGridImage,
        textAlign: 'Center'
    },
    {
        field: 'email',
        headerText: 'Email',
        width: '150',
        textAlign: 'Center'
    },
    {
        field: 'address',
        headerText: 'Direccion',
        width: '180',
        format: 'yMd',
        textAlign: 'Center'
    },
    {
        field: 'DNI',
        headerText: 'DNI',
        width: '105',
        format: 'C2',
        textAlign: 'Center'
    },

    {
        field: 'create_time',
        headerText: 'Desde',
        width: '100',
        format: 'yMd',
        textAlign: 'Center',
        template: (props) => moment(props.create_time).tz('Europe/Madrid').format('DD-MM-YY HH:mm')
    },
    {
        field: 'id',
        headerText: 'ID',
        width: '120',
        textAlign: 'Center',
        isPrimaryKey: true,
    },

]






AR Aishwarya Rameshbabu Syncfusion Team July 18, 2024 10:02 AM UTC

Hi Swadowmaster,


After reviewing the information provided, we have observed that there is a script issue when clicking the "Editar" button rendered in the command column of the Syncfusion Grid. It seems that you are only redirecting to a specified URL with the ID value upon clicking the command column button. We have created a simple sample that meets your requirements, and upon testing, we were unable to reproduce the reported script issue. When the button is clicked, it navigates to the specified URL without throwing any script error. Please review the attached sample and video demos for more details.


If you are still encountering an issue, please try to replicate it with the shared sample or provide a simple issue replication sample to validate it further.


Regards

Aishwarya R


Attachment: 189339_SampleAndVideo_2a8f3e8d.zip


S1 swadowmaster 102 July 18, 2024 09:15 PM UTC

Hi, 

I test your sample and it works perfectly but i found on my code the problem is the line "editSettinngs" when i remove it the code works !! this is my code working i dont know why this line break the code 

import React, { useEffect, useState, useRef } from 'react';
import { GridComponent, ColumnsDirective, ColumnDirective, Page, Selection, Inject, Edit, Toolbar, Sort, Filter, Search, Group, PdfExport, CommandColumn } from '@syncfusion/ej2-react-grids';
import { Header, Loader } from '../components';
import useAxios from '../utils/useAxios';
import { hermanosTabla } from '../data/info';
import { useNavigate } from 'react-router-dom';
import utils from '../utils';

const Hermanos = () => {
  const [dataLoaded, setDataLoaded] = useState(false);
  const selectionsettings = { persistSelection: true };
  const toolbarOptions = [{ text: 'Eliminar', id: 'Grid_delete', prefixIcon: 'e-delete' }, 'Buscar'];
  const sortSettings = {
    columns: [
      { field: 'name', direction: 'Ascending' }
    ]
  };
  const editing = { allowDeleting: true, allowEditing: true };
  const [data, setData] = useState([]);
  const api = useAxios();
  const navigate = useNavigate();
  const gridRef = useRef(null);
  utils.loadEspGrid(); //Load ESP languaje from utils

  const fetchData = async () => {
    try {
      const response = await api.get('/db/hermanos');
      setData(response.data.data);
      setDataLoaded(true);
    } catch (error) {
      console.error('Error fetching data', error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const clickHandler = async (args) => {
    if (args.item.id === 'Grid_delete' && gridRef.current) {
      const selectedRecords = gridRef.current.getSelectedRecords();

      for (const user of selectedRecords) {
        await api.delete(`/db/hermanos/${user.id}`);
      }
      fetchData();
    }
  };

  const commandClickHandler = (args) => {
    console.log(args)
    const record = args.rowData;
    if (args.commandColumn.buttonOption.content === 'Editar') {
      console.log(record.id)
      console.log(record)
      navigate(`/panel/editar-hermano/32`);

    //  if (record && record.id) {
/*     } else {
        console.error('El registro no es válido', record);
      }
  */  }
  };



  if (!dataLoaded) return (<Loader />);


  return (
    <div className="m-2 md:m-10 mt-24 p-2 md:p-10 bg-white rounded-3xl">
      <Header category="Gestión" title="Hermanos" />
      <GridComponent
        id="Grid"
        dataSource={data}
        width="auto"
        allowPaging
        selectionSettings={selectionsettings}
        pageSettings={{ pageCount: 12 }}

        //this line make the error idk why
        //editSettings={editing}

        toolbar={toolbarOptions}
        toolbarClick={clickHandler}
        ref={gridRef}
        allowSorting={true}
        sortSettings={sortSettings}
        allowFiltering={true}
        allowGrouping={true}
        locale='es-ES' // Configurar localización
        commandClick={commandClickHandler}
      >
        <ColumnsDirective>
          {hermanosTabla.map((item, index) => (
            <ColumnDirective key={index} {...item} headerText={item.headerText} />
          ))}
          <ColumnDirective headerText='Acciones' width='200' commands={[
            { buttonOption: { content: 'Editar', cssClass: 'e-flat' } },
          ]} />
        </ColumnsDirective>
        <Inject services={[Page, Selection, Toolbar, Edit, Sort, Filter, Group, PdfExport, CommandColumn]} />
      </GridComponent>
    </div>
  );
};

export default Hermanos;


Attachment: syncfusionSample_27b6e8e2.zip

updated code removing in inject Edit problem solved!

this make error 

        <Inject services={[Page, Selection, Toolbar, Edit, Sort, Filter, Group, CommandColumn]} />

this solved error :)
        <Inject services={[Page, Selection, Toolbar, Sort, Filter, Group, CommandColumn]} />

Marked as answer

AR Aishwarya Rameshbabu Syncfusion Team July 19, 2024 02:11 PM UTC

Hi Swadowmaster,


You are experiencing a problem with redirecting the page when clicking the "Editar" button only when the editSettings are configured in the Grid. When the editSettings are removed, the page redirection works properly when clicking the button. Before we can provide a solution to the issue you are facing, we require some additional information for validation. Please provide the following details:

1. Bind the actionFailure event to the Grid and console log the arguments to inform us of any exceptions or errors in that event.

2. Ensure the console log for any script issues and please share a screenshot of them.

3. Share the version of the Syncfusion package you are currently using.

4. Since we are unable to replicate the issue on our end, please share a simple sample demonstrating the issue, or attempt to reproduce the issue with the provided sample. This will assist us in further validating the issue.

Providing these details will allow us to validate the issue and to provide a more effective solution.


Regards

Aishwarya R



S1 swadowmaster 102 July 19, 2024 10:21 PM UTC

Hi, 

my problem solved removing Edit from Inject tag here is a video and i have this dependencies maybe it c


Attachment: sample_657fef99.zip


AR Aishwarya Rameshbabu Syncfusion Team July 22, 2024 02:06 PM UTC

Hi Swadowmaster,


We were unable to replicate the issue, with or without the Edit module injected. Please refer to the attached sample. It appears that the issue only occurs at your sample level when navigating to another page upon command click. However, we are pleased to hear that the issue has been resolved on your end.


Please get back to us if you need any other assistance.


Regards

Aishwarya R


Attachment: 189339Sample_ff021ad0.zip

Loader.
Up arrow icon