Search code examples
react-hooksreact-tablereact-datepickerreact-calendartimesheet.js

React JS UseState weekly display headers Time sheet


I am working on to implement a timesheet component in react using useState.I got bit confused with certain functionalities and how this is working behind the scenes(I am still learn guys).When I click the previousweek or nextweek control buttons, the dates are changing in a random way instead of showing the current month's nextweek dates or previousweek dates. The other issue also, whenever I I start typing in the inputs the dates on the headers are also changing randomly.

I am missing someting here, Would appreciate for a help out.Thanks

const TimeSheet = () => {

  const days = ["Mon", "Tue", "Wed", "Thurs", "Fri", "Sat", "Sun"];
  const [startDate, setStartDate] = useState(new Date());
  const [data, setData] = useState([
    { project: 'Project A', hours: [0, 0, 0, 0, 0, 0, 0], total: 0 },
    { project: 'Project B', hours: [0, 0, 0, 0, 0, 0, 0], total: 0 },
  ]);

  const handlePreviousWeek = () => {
    // setStartDate(new Date(startDate.setDate(startDate.getDate() - 7)));

    const prevWeek = new Date(startDate);
    prevWeek.setDate(startDate.getDate() - 7);
    setStartDate(prevWeek);
  };

  const handleNextWeek = () => {
    // setStartDate(new Date(startDate.setDate(startDate.getDate() + 7)));
    const nextWeek = new Date(startDate);
    nextWeek.setDate(startDate.getDate() + 7);
    setStartDate(nextWeek);
  };

  const handleAddRow = () => {
    setData([
      ...data,
      { project: `Project ${data.length + 1}`, hours: [0, 0, 0, 0, 0, 0, 0], total: 0 },
    ]);
  };

  const handleDeleteRow = (index) => {
    const updatedData = [...data];
    updatedData.splice(index, 1);
    setData(updatedData);
  };

  const handleSaveHours = () => {
    console.log('Hours saved:', data);
  };

  // const calculateTotal = (hours) => {
  //   let total = 0;
  //   for (let i = 0; i < hours.length; i++) {
  //     total += parseInt(hours[i]) || 0;
  //   }
  //   return total;
  // };

  const handleHoursChange = (projectIndex, dayIndex, value) => {
    const updatedData = [...data];
    updatedData[projectIndex].hours[dayIndex] = value;
    updatedData[projectIndex].total = updatedData[projectIndex].hours.reduce(
      (acc, cur) => acc + cur,
      0
    );
    setData(updatedData);
  };

  return (
    <div>
      <h1>Project Simple Time Sheet</h1>
      <div>
        <button onClick={handlePreviousWeek}>Previous Week</button>
        {/* <span>{startDate.toLocaleDateString("de-DE")}</span> */}
        <span>{`${startDate.toLocaleDateString('de-DE')} - ${new Date(
              startDate.setDate(startDate.getDate() + 6)
            ).toLocaleDateString('de-DE')}`}</span>
        <button onClick={handleNextWeek}>Next Week</button>
      </div>
      <table>
        <thead>
          <tr>
            <th>Project</th>

            {/* {Array.from({ length: 7 }).map((_, index) => (
              <th key={index}>{new Date(startDate.setDate(startDate.getDate() + 1)).toLocaleDateString("de-DE")}</th>
            ))} */}

          {days.map((day) => (
                  <th key={day}>
                    {day}
                    <br />
                    {new Date(
                      startDate.getFullYear(),
                      startDate.getMonth(),
                      startDate.getDate() + days.indexOf(day)
                    ).toLocaleDateString('de-DE')}
                  </th>
                ))}
            <th>Total</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {data.map((item, index) => (
            
            <tr key={index}>
              <td>{item.project}</td>
              {item.hours.map((hour, dayIndex) => (
                <td key={dayIndex}>
                  <input type="number" value={hour} onChange={(e) => handleHoursChange(index, dayIndex,     e.target.value)} />
                </td>
              ))}
              <td>
                {item.total}
            
              
              </td>
              <td><button onClick={() => handleDeleteRow(index)}>Delete</button></td>
            </tr>
          ))}
          <tr>
            <td></td>
            {Array.from({ length: 7 }).map((_, index) => <td key={index}></td>)}
            <td></td>
            <td></td>
          </tr>
        </tbody>
      </table>
      <button onClick={handleAddRow}>Add Row</button>
      <button onClick={handleSaveHours}>Save Hours</button>
      <button onClick={() => console.log('Hours submitted:', data)}>Submit</button>
    </div>
  );
};

export default TimeSheet;

Solution

  • The problem is in this line:

    <span>{`${startDate.toLocaleDateString('de-DE')} - ${new Date(
          startDate.setDate(startDate.getDate() + 6)
        ).toLocaleDateString('de-DE')}`}</span>
    

    Basically in new Date(startDate.setDate(startDate.getDate() + 6)) you are calling startDate.setDate(), which means you are modifying the internal value of startDate, and that is happening in every rendering!. To fix that I recommend using a utility function to offset dates, for example:

    const dateOffset = (date, offset) => {
      const newDate = new Date(date);
      newDate.setDate(date.getDate() + offset)
      return newDate;
    }
    

    Then replace the buggy line with:

    <span>{`${startDate.toLocaleDateString('de-DE')} - ${dateOffset(startDate, 6).toLocaleDateString('de-DE')}`}</span>
    

    Also, you can use it in handlePreviousWeek and handleNextWeek:

    const handlePreviousWeek = () => {
      setStartDate((currDate) => dateOffset(currDate, -7));
    };
    
    const handleNextWeek = () => {
      setStartDate((currDate) => dateOffset(currDate, 7));
    };