"use client"; import { DocumentIcon, TrashIcon } from "@heroicons/react/24/outline"; import { Bill } from "../lib/db-types"; import React, { FC } from "react"; import { useFormState } from "react-dom"; import { updateOrAddBill } from "../lib/actions/billActions"; import Link from "next/link"; import { gotoHome } from "../lib/actions/navigationActions"; // Next.js does not encode an utf-8 file name correctly when sending a form with a file attachment // This is a workaround for that const updateOrAddBillMiddleware = (locationId: string, billId:string|undefined, billYear:number|undefined, prevState:any, formData: FormData) => { // URL encode the file name of the attachment so it is correctly sent to the server const billAttachment = formData.get('billAttachment') as File; formData.set('billAttachment', billAttachment, encodeURIComponent(billAttachment.name)); return updateOrAddBill(locationId, billId, billYear, prevState, formData); } export interface BillEditFormProps { locationID: string, bill?: Bill, billYear?: number } export const BillEditForm:FC = ({ locationID, bill, billYear }) => { const { _id: billID, name, paid, attachment, notes, payedAmount } = bill ?? { _id:undefined, name:"", paid:false, notes:"" }; const initialState = { message: null, errors: {} }; const handleAction = updateOrAddBillMiddleware.bind(null, locationID, billID, billYear); const [ state, dispatch ] = useFormState(handleAction, initialState); const [ isPaid, setIsPaid ] = React.useState(paid); // redirect to the main page const handleCancel = () => { gotoHome(billYear ? `/?year=${billYear}` : undefined); }; const billPaid_handleChange = (event: React.ChangeEvent) => { setIsPaid(event.target.checked); } return(
{ // don't show the delete button if we are adding a new bill bill ? : null }
{state.errors?.billName && state.errors.billName.map((error: string) => (

{error}

))}
{ // attachment ? {decodeURIComponent(attachment.fileName)} : null }
{state.errors?.billAttachment && state.errors.billAttachment.map((error: string) => (

{error}

))}
{ isPaid && <>
{state.errors?.payedAmount && state.errors.payedAmount.map((error: string) => (

{error}

))}
}
{state.errors?.billNotes && state.errors.billNotes.map((error: string) => (

{error}

))}
{state.message &&

{state.message}

}
); }