Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda