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

195
Visualizações
ReactJS - Function to bulk overwrite nested usestate variable

I have a nested dictionary object with the following structure:

  const [fieldErrorMessage, setFieldErrorMessage] = useState({
    signinEmail: {
      show: false,
      message: "Error",
    },
    signinPassword: {
      show: false,
      message: "Error",
    },
    signupEmail: {
      show: false,
      message: "Error",
    },
    signupPassword: {
      show: false,
      message: "Error",
    },
    signupRegistrationToken: {
      show: false,
      message: "Error",
    },
  });

I created a function which should take in an array of nested dictionaries (e.g., signinEmail, signinPassword, ...) and set their value for their show key to false (without changing the value for the message property).

Here is my function:

function hideFieldErrors(setter, fieldNameArray) {
  fieldNameArray.forEach((fieldName) => {
    setter((prevState) => ({
      ...prevState,
      fieldName: {
        ...prevState.fieldName,
        show: false,
      },
    }));
  });
}

When I call it, the show values do not change. Why is that?

I'm calling it via this code:

hideFieldErrors(setFieldErrorMessage, [
    "signinEmail",
    "signinPassword",
    "signupEmail",
    "signupPassword",
    "signupRegistrationToken",
  ]);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The way you have used fieldName is not working as you expected. variable name(which is a string) should be wrapped with square brackets to make it an accessible property.

Try like below.

function hideFieldErrors(setter, fieldNameArray) {
  fieldNameArray.forEach((fieldName) => {
    setter((prevState) => ({
      ...prevState,
      [fieldName]: {
        ...prevState[fieldName],
        show: false,
      },
    }));
  });
}
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