import { FC, memo, useCallback, useEffect, useRef, useState } from "react" import classnames from "classnames" import get from "lodash/get" import set from "lodash/set" import styles from "./styles.module.scss" import { daysChoice, daysChoiceSelectionDefaultState, selectionChoices, useUserDayWishes, } from "../daysWishes.utils" import FormButton from "../../Form/FormButton/FormButton" type Props = { afterSubmit?: () => void | undefined } const DayWishesForm: FC = ({ afterSubmit }): JSX.Element => { const [selection, setSelection] = useState(daysChoiceSelectionDefaultState) const commentRef = useRef(null) const [userWishes, saveWishes] = useUserDayWishes() useEffect(() => { if (!userWishes) return const newSelection = get(userWishes, "dayWishes", []).reduce( (acc: selectionChoices, day: string) => ({ ...acc, [day]: true, }), daysChoice ) setSelection(newSelection) set(commentRef, "current.value", get(userWishes, "dayWishesComment", "")) }, [setSelection, commentRef, userWishes]) const onChoiceClick = useCallback( (id) => { setSelection({ ...selection, [id]: !selection[id], }) }, [selection, setSelection] ) const onChoiceSubmit = useCallback(() => { const comment = get(commentRef, "current.value", "") const days = daysChoice.map(({ id }) => id).filter((id) => selection[id]) saveWishes(days, comment) if (afterSubmit) afterSubmit() }, [selection, commentRef, saveWishes, afterSubmit]) return (
Mes jours de présence
    {daysChoice.map(({ id, label }) => (
  • ))}