Skip to content Skip to sidebar Skip to footer

Multiple Time Slots For Week Days Using ReactJS

If anyone can help me to optimize the following code. I am trying to create a registration page where users can select their time availability for selected days. Users have option

Solution 1:

To reduce redundancy you can look at what code is repeated and think of it more abstractly.

For example, the following code abstractly copies the entries for a day, removes an element, and updates state with new array for that day

// handle click event of the Remove button
const handleRemoveClickForMonday = (index) => {
  const list = [...monday];
  list.splice(index, 1);
  setMonday(list);
};

Now that you can abstractly operate on any day, think of a data structure that lends itself to looking up a specific day to operate on, like a map. In javascript it is common to use an object ({}) as a map of key-value pairs.

Convert state to object with day keys

const [days, setDays] = useState({
  monday: [{ FROM: "", TO: "" }],
  tuesday: [{ FROM: "", TO: "" }],
  wednesday: [{ FROM: "", TO: "" }],
  thursday: [{ FROM: "", TO: "" }],
  friday: [{ FROM: "", TO: "" }],
  saturday: [{ FROM: "", TO: "" }],
  sunday: [{ FROM: "", TO: "" }],
});

Update mounting effect hook (probably room for improvement here as well since just initializing data really; I didn't dig in on what the AVAILABILITY_XXX's were)

useEffect(() => {
  if (AVAILABILITY_MONDAY.length > 0)
    setDays((days) => ({
      ...days,
      monday: AVAILABILITY_MONDAY
    }));

  if (AVAILABILITY_TUESDAY.length > 0)
    setDays((days) => ({
      ...days,
      tuesday: AVAILABILITY_TUESDAY
    }));

  // etc for each day of the week
}, []);

Convert submit handler to access new state shape

const onSubmit = (data) => {
  const e = {
    target: {
      name: "AVAILABILITY_MONDAY",
      value: days.monday
    }
  };
  const f = {
    target: {
      name: "AVAILABILITY_TUESDAY",
      value: days.tuesday
    }
  };
  // etc for each day

  setForm(e);
  setForm(f);
  // etc

  navigation.next();
};

Convert handlers to take a day key

// handle input change
const handleInputChangeForDay = (e, day, index) => {
  const { name, value } = e.target;
  const list = [...days[day]];
  list[index][name] = value;
  
  setDays((days) => ({
    ...days,
    [day]: list
  }));
};

// handle click event of the Remove button
const handleRemoveClickForDay = (day, index) => {
  const list = [...days[day]];
  list.splice(index, 1);
  
  setDays((days) => ({
    ...days,
    [day]: list
  }));
};

// handle click event of the Add button
const handleAddClickForDay = (day) => () => {
  
  setDays((days) => ({
    ...days,
    [day]: [...days[day], { FROM: "", TO: "" }]
  }));
};

Create an array of key-value pairs from state and map each day

{Object.entries(days).map(([dayKey, day]) => {
  return day.map((x, i) => {
    return (
      <React.Fragment>
        Day: {dayKey}
        <select
          name="FROM"
          value={x.FROM}
          onChange={(e) => handleInputChangeForDay(e, dayKey, i)}
        >
          <option selected hidden>
            From
          </option>
          {timeList}
        </select>
        &nbsp;&nbsp;&nbsp;
        <select
          name="TO"
          value={x.TO}
          onChange={(e) => handleInputChangeForDay(e, dayKey, i)}
          placeholder="select your Institute"
        >
          <option selected hidden>
            TO
          </option>
          {timeList}
        </select>
        <div style={{ textAlign: "left", width: "84%" }}>
          {day.length !== 1 && (
            <label
              as="a"
              onClick={() => handleRemoveClickForDay(dayKey, i)}
              style={{ marginRight: "10px" }}
            >
              remove
            </label>
          )}

          {day.length - 1 === i && (
            <button
              type="button"
              as="a"
              onClick={handleAddClickForDay(dayKey)}
              style={{ marginRight: "10px" }}
            >
              add
            </button>
          )}
        </div>
      </React.Fragment>
    );
  });
})}

Edit optimize-react-codes-for-time-availabilty-based-on-week-day


Post a Comment for "Multiple Time Slots For Week Days Using ReactJS"