0

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.

1 Answer 1

1

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 },
}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.