Search code examples
reactjsuse-state

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:

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