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

147
Visualizações
Calling setState from callback updates the state in React Context half the time

Here is the CodeSandbox: https://codesandbox.io/s/competent-dream-8lcrt

I have implemented a modal with React context which exposes 1) the open state 2) the modal config 3) an open and close method

// ...

const onOpenDialog = (mode, config) => {
  setDialogMode(mode)
  if (config) {
    setDialogConfig(config);
  }
}

const onCloseDialog = () => {
  setDialogMode("");
  if (Object.keys(dialogConfig).length > 0) {
    setDialogConfig({})
  }
}

// ...

return (
  <Provider value={{ dialogMode, dialogConfig, onOpenDialog, onCloseDialog }}>
    {children}
  </Provider>
)

From the main component, I have an onClick handler that call the onOpenDialog method and pass an onSubmit and onClose callback in its config object (this onCloseDialog callback is the issue)

const { onOpenDialog, onCloseDialog } = useDialog()

// ...

const onClick = () => {
  onOpenDialog("add", {
    data: null,
    onSubmit: (data) => {
      console.log("Form Data: ", data)
    },
    onCancel: onCloseDialog
  })
}

And finally, I have a FormInModal component that call the two callbacks passed in the dialogConfig object when hitting submit and close.

const onSubmit = (data) => {
  dialogConfig.onSubmit({
    username: data.username,
    password: data.password
  })
}

const onCancel = () => {
  dialogConfig.onCancel()
}

Steps to reproduce:

  1. Click on Open
  2. You should see in the console that 1) The dialog opens 2) The config input that was passed to the Dialog config has data, onSubmit and onCancel, the config input has been set in the dialogConfig state
  3. Click on Cancel, you should see that 1) The dialog closes 2) The dialogConfig state is empty 3) the dialogConfig state is not reseted

To be fair 3. works half of the time. This is weird because the dialogConfig state is always updated when the dialog opens. You can see on the React Dev tool that the state update only half the time

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is a known problem in React when trying to access the state from a function closures. The old state is captured at the closure creation and returned by the function even though the state has updated.

One way to solve the issue is to access the updated state with:

setState(previousState => newState) instead of setState(newState)

The answer from the react community: Function that read an outdated sate

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