Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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",
  ]);

>Solution :

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,
      },
    }));
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading