0

anyone has an idea what causes the ff issue ? I cannot insert new object to a key object in my arrays of objects for example I wanna insert new email to emails at index 1 when I push to that it causes error cannot add property 1 , onject is not extensible in .

Ideads and help would be much appreciated. Thank.s

#code

const addEmail = (id: number) => {
    console.log('...RegionalList',RegionalList)
    const regionalList = [...RegionalList];
    const index = regionalList
      .map((prop: IRegionalList) => prop.id)
      .indexOf(id);

    console.log('regionalList[index].emails' , regionalList[index].emails)

    regionalList[index].emails.push({
      emailAddress: '',
      firstName: '',
      lastName: '',
      id: Math.floor(Math.random() * 999),
      fetching: false,
    });
    setRegionalList(regionalList);
  };

#object where I am inserting on regionalist arrays of object the value of this variable const regionalList = [...RegionalList];

[
    {
        "id": 4,
        "name": "Associate Director of Construction Ops",
        "column": "associateDirectorofConstructionOps",
        "emails": [
            {
                "id": 79,
                "emailAddress": "[email protected]",
                "firstName": "James",
                "lastName": "Crawford"
            }
        ]
    },
    {
        "id": 5,
        "name": "CAM Manager",
        "column": "camManager",
        "emails": [
            {
                "id": 77,
                "emailAddress": "[email protected]",
                "firstName": "Jennifer",
                "lastName": "Jones"
            }
        ]
    },
]

#another snippet

 const setEmailValue = (event: any, regionalId: number, index: number) => {
    setRegionalList((prevState: IRegionalList[]) => {
      const newState = prevState.map((prop: IRegionalList) => {
        if (prop.id === regionalId) {
          prop.emails[index] = { emailAddress: event.target.value, id: null };
          return { ...prop };
        }
        return prop;
      });
      return newState;
    });
  }

#another snippet

 useEffect(() => {
    if (selectedRow) {
      console.log('selectedRow' , selectedRow)
      // Set selected row data
      setData({
        regionName: selectedRow['regionName'],
        marketName: selectedRow['marketName'],
        subRegionName: selectedRow['subRegionName'],
      });

      let regional = [...RegionalList];
      for (const k in selectedRow) { 
        regional.map((prop: IRegionalList) => {
          if (prop.column === k) {
            prop.emails = selectedRow[k] ? selectedRow[k] : []
          }
        })
      }
      console.log('regional:', regional);
      setRegionalList(regional);
    }
  }, [selectedRow]);
7
  • 1
    The array is frozen. You're not supposed to mutate the state anyway. I assume this is React finally enforcing this. Another question for the same thing: Array.push TypeError: Cannot add property 0, object is not extensible Commented Nov 10, 2022 at 11:58
  • so what is the correct or the answer to it Sir ? right now the freezing is a bit vague for me Commented Nov 10, 2022 at 12:00
  • how not to freeze it ? Commented Nov 10, 2022 at 12:01
  • DO NOT UNFREEZE IT. YOU ARE REQUIRED TO NOT MUTATE THE STATE. Commented Nov 10, 2022 at 12:01
  • Doesn't seems like regionalList is a React state. Where is setRegionalList defined? Can you share some more code? Commented Nov 10, 2022 at 12:03

1 Answer 1

1

As you cannot mutate the state as in your code above, you have to create and return a new array, so try:

const addEmail = (id: number) => {
  setRegionalList(list => list.map(item => {
    if (item.id === id) {
      return {
        ...item,
        emails: [
           ...item.emails,
           {
             emailAddress: '',
             firstName: '',
             lastName: '',
             id: Math.floor(Math.random() * 999),
             fetching: false,
           }
        ]
      }
    }

    return item;
  }))
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Sir , I have another question Sir maybe you have an idea with this one stackoverflow.com/questions/74389737/…

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.