search envelope-o feed check
Home Unanswered Active Tags New Question
user comment-o

Previous And next not working when Adding more features to it..?

Asked by Siva
1 year ago.
import React, {useEffect, useState} from 'react';
import * as ReactBootStrap from "react-bootstrap";
import { Modal, Button, OverlayTrigger, Tooltip } from "react-bootstrap";
import "../Admin";
import profile from "../images/smrft.jpg";
import { Navbar, Nav } from "react-bootstrap";
import { useNavigate } from "react-router-dom";
import {BrowserRouter as Router,Link,useParams} from "react-router-dom";
import Viewemp from "./Viewemp";
import "../Components/AdminCalendar.css";
import {DayPilot, DayPilotScheduler} from "daypilot-pro-react";
import Fade from '@material-ui/core/Fade';

function Admincalendar() {
  const params = useParams();
  const id = params.id;

  let [name, setName] = useState("");
  const [eventData, setEventData] = useState([]);
  let [summarydata, setSummaryData] = useState({workingdays: ' ',leavedays: ' ',overtime: ' '});
  const [show, setShow] = useState(false);
  const [Otbox, setOtbox] = useState(false);
  const [leavebox, setleavebox] = useState(false);
  let [prevMonthPayload, setprevMonthPayload] = useState("");
  let [nextMonthPayload, setnextMonthPayload] = useState("");

  const timesheetRef = React.createRef();

  const handleClose = () => setShow(false);
    useEffect(() => {
      handleClose();
    }, []);

    const handleOtDialog = () => setOtbox(false);
    useEffect(() => {
      handleOtDialog();
    }, []);

    const handleleaveDialog = () => setleavebox(false);
    useEffect(() => {
      handleleaveDialog();
    }, []);

    function timesheet() {
      return timesheetRef.current.control;
    }
    
  let events = {
    locale: "en-us",
    onBeforeEventRender: (args) => {
      if (!args.data.barColor) {
        args.data.barColor = "red";
      }
      args.data.borderColor = "darker";
      args.data.fontColor = "black";
    },
    onBeforeRowHeaderRender: (args) => {
        args.row.horizontalAlignment = "center";
      },
      crosshairType: "Header",
      timeHeaders: [{"groupBy":"Hour"},{"groupBy":"Cell","format":"mm"}],
      scale: "CellDuration",
      cellDuration: 30,
      viewType: "Days",
      startDate: DayPilot.Date.today().firstDayOfMonth(),
      days: DayPilot.Date.today().daysInMonth(),
      showNonBusiness: true,
      businessWeekends: false,
      floatingEvents: true,
      eventHeight: 30,
      groupConcurrentEvents: false,
      eventStackingLineHeight: 100,
      allowEventOverlap: true,
      allowAllEvent: true,   
      timeRangeSelectedHandling: "Enabled",
  }

const month = DayPilot.Date.today().getMonth()+1;
const empid = {
  id: id,
  month:month
};
async function fetchCalendarData() {
    const {data: calendarData} = await DayPilot.Http.post("http://127.0.0.1:7000/attendance/EmpcalendarId",empid); 
    setEventData(calendarData); 
  } 
  useEffect(() => {
   fetchCalendarData();
  }, []);

async function SummaryData() {
  const {data: summarydetails} = await DayPilot.Http.post("http://127.0.0.1:7000/attendance/SummaryDetails",empid)
    summarydetails.forEach((emp) => {
      let empdata = {};
      empdata["id"] = emp.id;
      empdata["month"] = emp.month;
      empdata["name"] = emp.name;
      empdata["workingdays"] = emp.workingdays;
      empdata["leavedays"] = emp.leavedays;
      empdata["overtime"] = emp.overtime;
      setName(emp.name);
      setSummaryData({
        workingdays: emp.workingdays,
        leavedays: emp.leavedays,
        overtime: emp.overtime
      });   
    });
}

  async function previous() {
    const currentmonthstartdate = timesheet().visibleStart();
    const prevmonthstartdate = currentmonthstartdate.addMonths(-1);
    const prevMonth = prevmonthstartdate.getMonth()+1;
    prevMonthPayload = {
      id: id,      
      month: prevMonth
    };
    setprevMonthPayload(prevMonthPayload);  
    const { data: calendarData } = await DayPilot.Http.post("http://127.0.0.1:7000/attendance/EmpcalendarId", prevMonthPayload);
    timesheet().update({
      startDate: prevmonthstartdate,
      days: prevmonthstartdate.daysInMonth(),
      events: calendarData
    });
  }
async function previousmonthsummary() {
  const {data: summarydetails} = await DayPilot.Http.post("http://127.0.0.1:7000/attendance/SummaryDetails",prevMonthPayload)
  summarydetails.forEach((emp) => {
    let empdata = {};
    empdata["id"] = emp.id;
    empdata["month"] = emp.month;
    empdata["name"] = emp.name;
    empdata["workingdays"] = emp.workingdays;
    empdata["leavedays"] = emp.leavedays;
    empdata["overtime"] = emp.overtime;
    setName(emp.name);
    setSummaryData({
      workingdays: emp.workingdays,
      leavedays: emp.leavedays,
      overtime: emp.overtime
    });   
  });
}
 
  async function next() {
    const currentmonthstartdate = timesheet().visibleStart();
    const nextmonthstartdate = currentmonthstartdate.addMonths(1);
    const nextMonth = nextmonthstartdate.getMonth()+1;
    nextMonthPayload = {
      id: id,
      month: nextMonth
    };
    setnextMonthPayload(nextMonthPayload);
    const { data: calendarData } = await DayPilot.Http.post("http://127.0.0.1:7000/attendance/EmpcalendarId", nextMonthPayload);
    timesheet().update({
      startDate: nextmonthstartdate,
      days: nextmonthstartdate.daysInMonth(),
      events: calendarData
    });
  }

  async function nextmonthsummary() {
    const {data: summarydetails} = await DayPilot.Http.post("http://127.0.0.1:7000/attendance/SummaryDetails",nextMonthPayload)
    summarydetails.forEach((emp) => {
      let empdata = {};
      empdata["id"] = emp.id;
      empdata["month"] = emp.month;
      empdata["name"] = emp.name;
      empdata["workingdays"] = emp.workingdays;
      empdata["leavedays"] = emp.leavedays;
      empdata["overtime"] = emp.overtime;
      setName(emp.name);
      setSummaryData({
        workingdays: emp.workingdays,
        leavedays: emp.leavedays,
        overtime: emp.overtime
      });   
    });
}

const handlePreviousMonth = () => {
  previous();
  previousmonthsummary();
}

const handleNextMonth = () => {
  next();
  nextmonthsummary();
}
     
return (
  <div>
    <div>
      <style>{"body { background-color: rgb(255, 255, 255); }"}</style>
        <div className="main"></div>
        <div className="logo">
          <img src={profile} className="smrft_logo" alt="logo" />
        </div>
    </div>
      <Navbar style={{ width: "500px", marginLeft: "500px", marginTop: "-90px" }}>
        <Navbar.Toggle aria-controls="navbarScroll" />
        <Navbar.Collapse id="navbarScroll">
          <Nav className="mr-auto my-2 my-lg-0" style={{ maxHeight: "200px" }} navbarScroll>
            <Nav.Link as={Link} to="/">
              <div style={{ color: "green", fontFamily: "cursive" }}>Home</div>
            </Nav.Link>
            <Nav.Link as={Link} to="/Admin/Viewemp">
              <div style={{ color: "green", fontFamily: "cursive" }}>Employee Details</div>
            </Nav.Link>
          </Nav>
        </Navbar.Collapse>
      </Navbar>
      <br/>
      <br/>
      <br/>
      <i style={{float:"right", color: "green",fontSize:"30px"}}  onClick={() => {setShow(true);SummaryData(); }}  data-toggle="modal"className="bi bi-journal-text"/>
      <div className='modal-dialog'>
      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>SUMMARY</Modal.Title>
            </Modal.Header>
              <Modal.Body>
              <div>
                <b>Employee Id: </b>{id}
              <br/>
                <b>Name: </b>{name}
              <br/>
                <b>Over Time Days: </b>{summarydata.overtime} <i style={{color: "green",fontSize:"20px"}} onClick={() => setOtbox(true)} className="bi bi-file-plus"></i>
                <div style={{float:"right"}}>
                  <Fade in={Otbox}>
                    <ReactBootStrap.Table onClick={() => setOtbox(false)} className="table table-hover table-bordered table-striped">
                    {/* <i style={{color: "green",fontSize:"20px"}} onClick={() => setOtbox(false)} className="bi bi-cross"></i> */}
                        <thead>
                            <tr>
                              <th>Date</th>
                              <th>Worked Hours</th>
                              <th>Ovetime Hours</th>
                            </tr>
                        </thead>
                        <tbody>
                          <tr key={id}>
                          <td>{}</td>
                          <td>{name}</td>
                          <td>{id}</td>
                          </tr>
                        </tbody>
                    </ReactBootStrap.Table>
                  </Fade>
                </div>
              <br/>
                <b>Working Days: </b>{summarydata.workingdays}
              <br/>
                <b>Leave Days: </b>{summarydata.leavedays} <i style={{color: "green",fontSize:"20px"}} onClick={() => setleavebox(true)} className="bi bi-file-plus"></i>
                <div style={{float:"right"}}>
                  <Fade in={leavebox}>
                    <ReactBootStrap.Table className="table table-hover table-bordered table-striped">
                        <thead>
                            <tr>
                              <th>Date</th>
                              <th>CL</th>
                              <th>SL</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </ReactBootStrap.Table>
                  </Fade>
                </div>
              <br/>
              </div>
              </Modal.Body>
      </Modal>
      </div>
        <div className={"toolbar"}>
          <button style={{borderRadius:10}} className="mx-1 btn btn-outline-info btn-sm px-3" type="button" onClick={(ev) => {handlePreviousMonth()}}>PREVIOUS</button>
          <button style={{borderRadius:10}} className="mx-1 btn btn-outline-info btn-sm px-3" type="button" onClick={(ev) => {handleNextMonth()}}>NEXT</button>
        </div>
      <div className='AdminCalendar'>
        <DayPilotScheduler 
          {...events}
          ref={timesheetRef}
          events={eventData}
        />
      </div>
      </div>
    );
}
export default Admincalendar;

Is the code correct..Previous and next was not working after clicking summary modal is opened...When I click previous button it should go to previous button after that when I click summary button It should show the previous month summary detaiils in the summary modal and it should remain in previous button...But according to this code it was moving to previous month for fraction of month and in the summary modal it shows previous month details there is no issue in that but It goes to current month when I click previous month summary modal

Answer posted by Dan Letecky [DayPilot]
1 year ago.

I recommend you to review the code and remove duplicate parts - that makes it confusing and error-prone. You define three functions that do the same thing.

There are also other issues, like calling setSummaryData() in summarydetails.forEach() which makes no sense and is misleading. The output of useState() should be defined with "const" instead of "let" - if you do that, you will find more issues. Also, make sure that you only store necessary things in the state, as every state change invokes a new render.

To get a better understanding how useEffect() and function component work, I recommend reading this article:
https://overreacted.io/a-complete-guide-to-useeffect/

One DayPilot-specific issue is that you define events using events={eventData} and also use update() to set the events. Never combine these two approaches - the changes made using direct API will be overwritten by the <DayPilotScheduler> attribute values on every state change.

This question is more than 1 months old and has been closed. Please create a new question if you have anything to add.