Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda