import { Button, Stack, TextField } from "@mui/material"; import { DateTimePicker, LocalizationProvider } from "@mui/x-date-pickers"; import { AdapterLuxon } from "@mui/x-date-pickers/AdapterLuxon"; import { WeightEntry } from "@/components/Weight/models/WeightEntry"; import { useAddWeightEntryQuery, useBodyWeightQuery, useEditWeightEntryQuery } from "@/components/Weight/queries"; import { LoadingPlaceholder } from "@/core/ui/LoadingWidget/LoadingWidget"; import { Form, Formik } from "formik"; import { DateTime } from "luxon"; import { useState } from 'react'; import { useTranslation } from "react-i18next"; import * as yup from 'yup'; interface WeightFormProps { weightEntry?: WeightEntry, closeFn?: () => void, } export const WeightForm = ({ weightEntry, closeFn }: WeightFormProps) => { const weightEntriesQuery = useBodyWeightQuery(); const addWeightQuery = useAddWeightEntryQuery(); const editWeightQuery = useEditWeightEntryQuery(); const [dateValue, setDateValue] = useState(weightEntry ? DateTime.fromJSDate(weightEntry.date) : DateTime.now); const [t, i18n] = useTranslation(); const validationSchema = yup.object({ weight: yup .number() .min(30, 'Min weight is 30 kg') .max(300, 'Max weight is 300 kg') .required('Weight field is required'), }); if (weightEntriesQuery.isLoading) { return ; } return ( ( { // Edit existing weight entry if (weightEntry) { weightEntry.weight = values.weight; weightEntry.date = values.date; editWeightQuery.mutate(weightEntry); // Create a new weight entry } else { weightEntry = new WeightEntry(values.date, values.weight); addWeightQuery.mutate(weightEntry); } if (closeFn) { closeFn(); } }} > {formik => (
{ if (newValue) { formik.setFieldValue('date', newValue.toJSDate()); } setDateValue(newValue); }} />
)}
) ); };