Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
How to set previous state on useState using Typescript

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!