How to use CRUD in React Functional Component with Node.js

Hi,
I'm developing a MERN stack project with a scheduler but all guide support only class component in react. I need to use CRUD with functional component in React with Node js.

This is I tried to code
import React, { useEffect, useState } from 'react';
import "./style.css";
import {Schedule, Inject, ScheduleComponent, ViewsDirective,
        ViewDirective, Day, Week, WorkWeek, Month, 
        Agenda, Resize, DragAndDrop } from "@syncfusion/ej2-react-schedule"
/*         import { DataManager, UrlAdaptor } from '@syncfusion/ej2-data'; */
        
const Calender = () => {
    
    const [randevu, setRandevu] = useState();
    
    useEffect (()=>{
        console.log(randevu)
    })

    
    const firstAppointment =[
        {
            Id: 1,
            Subject: 'first meeting',
            StartTime: new Date(2021, 4, 3, 9, 30),
            EndTime: new Date(2021, 4, 3, 11, 0)
        },
        {
            Id: 2,
            Subject: 'second meeting',
            StartTime: new Date(2021, 4, 3, 10, 30),
            EndTime: new Date(2021, 4, 3, 11, 30)
        },
        {
            Id: 3,
            Subject: 'third meeting',
            StartTime: new Date(2021, 4, 3, 10, 30),
            EndTime: new Date(2021, 4, 3, 11, 30)
        },
    ];
    
    
    
    return (
        <div>
            <ScheduleComponent id="Schedule"
                height="550px" ref={data => setRandevu(data)} eventSettings={{dataSource: firstAppointment}} >
                <ViewsDirective>
                <ViewDirective option="Day" />
                <ViewDirective option="Week" />
                <ViewDirective option="WorkWeek" />
                <ViewDirective option="Month" />
                <ViewDirective option="Agenda" />
                </ViewsDirective>
                <Inject
                services={[
                    Day,
                    Week,
                    WorkWeek,
                    Month,
                    Agenda,
                    Resize,
                    DragAndDrop
                ]}
                />
            </ScheduleComponent>
        </div>
    )
}

export default Calender;


This is the example code I found;

import { render } from 'react-dom';
import './index.css';
import * as React from 'react';
import { ScheduleComponentViewsDirectiveViewDirectiveDayWeekWorkWeekMonthAgendaInjectResizeDragAndDrop } from '@syncfusion/ej2-react-schedule';
import { extend } from '@syncfusion/ej2-base';
import { DatePickerComponent } from '@syncfusion/ej2-react-calendars';
import { SampleBase } from './sample-base';
import { PropertyPane } from './property-pane';
import * as dataSource from './datasource.json';
import { DataManagerQueryUrlAdaptor } from '@syncfusion/ej2-data';
/**
 * Schedule Default sample
 */
export class Default extends SampleBase {
  constructor() {
    super(...arguments);
    this.data = new DataManager({
      url: 'http://localhost:54738/Home/LoadData'// Here need to mention the web api sample running path
      crudUrl: 'http://localhost:54738/Home/UpdateData',
      crossDomain: true,
      adaptor: new UrlAdaptor
    });
  }
  render() {
    return (<div className='schedule-control-section'>
      <div className='col-lg-9 control-section'>
        <div className='control-wrapper'>
          <ScheduleComponent height='650px' ref={schedule => this.scheduleObj = schedule} selectedDate={new Date(2019010)} eventSettings={dataSource: this.data }} >
            <ViewsDirective>
              <ViewDirective option='Day' />
              <ViewDirective option='Week' />
              <ViewDirective option='WorkWeek' />
              <ViewDirective option='Month' />
              <ViewDirective option='Agenda' />
            </ViewsDirective>
            <Inject services={[DayWeekWorkWeekMonthAgendaResizeDragAndDrop]} />
          </ScheduleComponent>
        </div>
      </div>
    </div>);
  }
}

render(<Default />document.getElementById('sample'));

5 Replies 1 reply marked as answer

HB Hareesh Balasubramanian Syncfusion Team May 5, 2021 03:07 PM UTC

HI Muhammet, 

Greetings from Syncfusion Support..! 

We have prepared a CRUD sample based on your shared query “need to use CRUD sample with functional component” using functional component at the client-side, which can be downloaded from the following link. 


const dataManager = new DataManager({ 
  crossDomain: true, 
  adaptor: new UrlAdaptor() 
}); 


function DefaultSample() { 
  return ( 
    <div> 
      <ScheduleComponent 
        width="100%" 
        height="650px" 
        selectedDate={new Date(2017, 5, 4)} 
        eventSettings={{ dataSource: dataManager }} 
      > 
        <Inject 
          services={[Day, Week, WorkWeek, Month, Agenda, Resize, DragAndDrop]} 
        /> 
      </ScheduleComponent> 
    </div> 
  ); 
render(<DefaultSample />, document.getElementById("sample")); 

Kindly try the above solution and get back to us if you need any further assistance. 

We will be happy to assist you..! 

Regards, 
Hareesh 



MU Muhammet May 5, 2021 08:39 PM UTC

Thanks for reply me.

I am confused about something. When I drag and drop or edit, will the data going to the database be updated through this (the code below) process? 

Especially, I need an explanation about URL (crudUrl: "http://localhost:54738/Home/UpdateData",)  I have to use "Crud.saveEvent" or "Crud.deleteEvent" Because all buttons (edit, delete and update) redirect "/UpdateData" how can I code controllers in Node.js?


ajax.js:94 POST http://localhost:3000/calender/UpdateData 500 (Internal Server Error)
(anonymous)@ajax.js:94
Ajax.send@ajax.js:62
DataManager.saveChanges@manager.js:384
(anonymous)@crud.js:171
Observer.notify@observer.js:84
ComponentBase.trigger@component-base.js:209
Crud.saveEvent@crud.js:160

const dataManager = new DataManager({
  url: "http://localhost:54738/Home/LoadData",
  crudUrl: "http://localhost:54738/Home/UpdateData",
  crossDomain: true,
  adaptor: new UrlAdaptor()
});



HB Hareesh Balasubramanian Syncfusion Team May 6, 2021 12:27 PM UTC

Hi Muhammet, 

Thanks for the update. 

We have validated your shared query at our end and let you know that “UpdateData” method will perform all the CRUD (Create, edit, delete) actions based on the “param.action” arguments and “LoadData” method will get appointments from the Database. Kindly refer to the below snippets. 

[To get appointments using ”LoadData”] 
        public JsonResult LoadData(Params param)  // Here we get the Start and End Date and based on that can filter the data and return to Scheduler 
        { 
            DateTime start = param.StartDate; 
            DateTime end = param.EndDate; 
            var data = db.ScheduleEventDatas.Where(app => (app.StartTime >= start && app.StartTime <= end) || (app.RecurrenceRule != null && app.RecurrenceRule != "")).ToList();  // Here filtering the events based on the start and end date value. 
            return Json(data, JsonRequestBehavior.AllowGet); 
        } 

[performs CRUD action using “UpdateData”] 
        public JsonResult UpdateData(EditParams param) 
        { 
            if (param.action == "insert" || (param.action == "batch" && param.added != null)) // this block of code will execute while inserting the appointments 
            { 
                var value = (param.action == "insert") ? param.value : param.added[0]; 
                int intMax = db.ScheduleEventDatas.ToList().Count > 0 ? db.ScheduleEventDatas.ToList().Max(p => p.Id) : 1; 
                DateTime startTime = Convert.ToDateTime(value.StartTime); 
                DateTime endTime = Convert.ToDateTime(value.EndTime); 
                ScheduleEventData appointment = new ScheduleEventData() 
                { 
                    Id = intMax + 1, 
                    StartTime = startTime, 
                    EndTime = endTime, 
                    Subject = value.Subject, 
                    Location = value.Location, 
                    Description = value.Description, 
                    IsAllDay = value.IsAllDay, 
                    StartTimezone = value.StartTimezone, 
                    EndTimezone = value.EndTimezone, 
                    RecurrenceRule = value.RecurrenceRule, 
                    RecurrenceID = value.RecurrenceID, 
                    RecurrenceException = value.RecurrenceException 
                }; 
                db.ScheduleEventDatas.InsertOnSubmit(appointment); 
                db.SubmitChanges(); 
            } 
            if (param.action == "update" || (param.action == "batch" && param.changed != null)) // this block of code will execute while updating the appointment 
            { 
               var value = (param.action == "update") ? param.value : param.changed[0]; 
                var filterData = db.ScheduleEventDatas.Where(c => c.Id == Convert.ToInt32(value.Id)); 
                if (filterData.Count() > 0) 
                { 
                    DateTime startTime = Convert.ToDateTime(value.StartTime); 
                    DateTime endTime = Convert.ToDateTime(value.EndTime); 
                    ScheduleEventData appointment = db.ScheduleEventDatas.Single(A => A.Id == Convert.ToInt32(value.Id)); 
                    appointment.StartTime = startTime; 
                    appointment.EndTime = endTime; 
                    appointment.StartTimezone = value.StartTimezone; 
                   appointment.EndTimezone = value.EndTimezone; 
                    appointment.Subject = value.Subject; 
                    appointment.Location = value.Location; 
                    appointment.Description = value.Description; 
                    appointment.IsAllDay = value.IsAllDay; 
                    appointment.RecurrenceRule = value.RecurrenceRule; 
                    appointment.RecurrenceID = value.RecurrenceID; 
                    appointment.RecurrenceException = value.RecurrenceException; 
                } 
                db.SubmitChanges(); 
            } 
            if (param.action == "remove" || (param.action == "batch" && param.deleted != null)) // this block of code will execute while removing the appointment 
            { 
               if (param.action == "remove") 
                { 
                    int key = Convert.ToInt32(param.key); 
                    ScheduleEventData appointment = db.ScheduleEventDatas.Where(c => c.Id == key).FirstOrDefault(); 
                    if (appointment != null) db.ScheduleEventDatas.DeleteOnSubmit(appointment); 
                } 
                else 
                { 
                    foreach (var apps in param.deleted) 
                    { 
                        ScheduleEventData appointment = db.ScheduleEventDatas.Where(c => c.Id == apps.Id).FirstOrDefault(); 
                        if (apps != null) db.ScheduleEventDatas.DeleteOnSubmit(appointment); 
                    } 
                } 
                db.SubmitChanges(); 
            } 
            var data = db.ScheduleEventDatas.ToList(); 
            return Json(data, JsonRequestBehavior.AllowGet); 
        } 

Kindly try the above code snippets and get back to us if you need any further assistance. 

We will be happy to assist you..! 

Regards, 
Hareesh 


Marked as answer

MU Muhammet May 6, 2021 06:19 PM UTC

Thanks for all your answers, I solved all problems.
In the last comment about the CRUD sample, I really had trouble understanding the codes as they seemed too long and complicated. It may not be a good practice, but because it is easier and shorter to read, I shared the codes I wrote below.

import Appointment from "../models/appointment.js"

//CRUD SAMPLE
export const updateAppointment = (req, res) => {
    
    const dataChanged = req.body.changed[0];
    const dataAdded = req.body.added[0];
    const dataDeleted = req.body.deleted[0];
 

    if(req.body.changed.length>0 ) {
        //Update an Appointment
        Appointment.updateOne({_id: dataChanged._id}, dataChanged , (err)=>{
            if(err) {
                console.log(err);
            }else{
                console.log("Succesfully updated");
            }
        })
        res.redirect("/calender/LoadData")

    }else if(req.body.added.length>0) {
        //Create an Appointment
          const createAppointment =  new Appointment ({
                   Subject: dataAdded.Subject,
                   StartTime: dataAdded.StartTime,
                   EndTime: dataAdded.EndTime,
                   Description:dataAdded.Description,
               });
           createAppointment.save();
           console.log("succesfully added");
           res.redirect("/calender/LoadData")
           
        }else if(req.body.deleted.length>0) {
            //Delete an Appointment
            Appointment.deleteOne({_id: dataDeleted._id}, (err)=>{
                if(err){
                    console.log(err);
                }else{
                    console.log("Succesfully Deleted");
                }
            });
            res.redirect("/calender/LoadData")

    }else if(err) {
        console.log(err);
    }
    

};

//Display appointments from DataBase (LOAD DATA)
export const loadAppointmentData = (req, res) => {
   Appointment.find()
        .then(foundAppointment=>res.json(foundAppointment))
};


NR Nevitha Ravi Syncfusion Team May 7, 2021 06:26 AM UTC

Hi Muhammet, 

Thanks for your update. 

The code shared by us for CRUD were in C#, so that it is different from yours. We are happy that your problem has been resolved at your end. Please get back to us if you need any further assistance. 

Regards, 
Nevitha 


Loader.
Up arrow icon