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

React update nested object state

In one of my react project, I have initial state as follow:

 const initialValues = {
    en: {
      notificationTitle: "",
      notificationSubTitle: "",
    },
    hi: {
      notificationTitle: "",
      notificationSubTitle: "",
    },
    webUrl: "",
  };

  const [formData, setFormData] = useState(initialValues);

I’m passing this state as a props to child components which I’m using them as tabs like this

{selectedTab === "EnNotification" ? (
        <EnNotification
          formData={formData}
          setFormData={setFormData}
        />
      ) : (
        <HiNotification
          formData={formData}
          setFormData={setFormData}
        />
      )}

when I enter the data in one tab suppose in EnNotification tab the state updates but when I tried to switch the tab it give me the following error:

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

TypeError: Cannot read properties of undefined (reading 'notificationTitle')

My input component looks like:

 <Input
          value={formData.en.notificationSubTitle || ""}
          placeholder="Notification Sub Title"
          onChange={(event) => {
            const tempval = event.target.value;
            setFormData((data) => ({
              en: { ...data.en, notificationSubTitle: tempval },
            }));
          }}
        />

I think the problem is from only one component I’m able to update the state, but I want it should be updated from both.

Thank you.

>Solution :

When you are updating the formData state, before replacing the object en, you should also copy the rest of the value from the current state. Try this instead:

setFormData((data) => ({
 ...data,
 en: { ...data.en, notificationSubTitle: tempval },
}));
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