I have the current state:
const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice)
My type for InvoiceType is :
customer_email: string
customer_name: string
description: string
due_date: string
status: FilterButtonState
total: number
line_items: LineItemType[]
I am trying to modify state in my form to modify previous state using an input field like follows:
<input
...otherAttributes
onChange={(ev: React.ChangeEvent<HTMLInputElement>): void =>
setInvoice((prevState) => ({
...prevState,
customer_name: ev.target.value
}))
/>
But I keep getting the following Type error: Argument of type '(prevState: InvoiceType | null) => { customer_name: string; customer_email?: string | undefined; description?: string | undefined; due_date?: string | undefined; status?: FilterButtonState | undefined; total?: number | undefined; line_items?: LineItemType[] | undefined; }' is not assignable to parameter of type 'SetStateAction<InvoiceType | null>'
I am not sure how to structure this so that I can get around this issue. Thanks for the help.
You defined the state as InvoiceType | null, so prevState can be null. You must add a guard before using it:
prevState => prevState ? { ...prevState, customer_name: ev.target.value } : null
The another approach is to define the state so it always has a value: useState(invoice || emptyInvoice). And then you can keep your code for the update.