Home > front end >  How change setState of object in other object in React?
How change setState of object in other object in React?

Time:07-04

I created a state of objects in React, but i had need to increase other object into the same state. Howerer, i can't use the setState() property because cause a re-render (infinite loop).

My state:

const [testObject, setTestObject] = useState({
       id: 0,          
       telephone: 123,            
       personalData: {
            name: '',
            alias: '',
            gender: ''
        }
    })

The error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

I tried to find a solution for it, but i can't solve it:

setTestObject({...testObject, personalData: {
        ...testObject, name: 'McDonnell DC-10'
    }})

Where am i wrong?

CodePudding user response:

You just need to specify you're using personalData, you're along the right lines.

setTestObject({...testObject, personalData: {
        ...testObject.personalData, name: 'McDonnell DC-10'
    }})

You can even use the old state as a parameter for better performance.

setTestObject(testObject => { return {...testObject, personalData: {
        ...testObject.personalData, name: 'McDonnell DC-10'
    }}})

CodePudding user response:

What you can do to avoid the infinite loop is add the code inside a useEffect(), like this:

 useEffect(() => {
    setTestObject({
      ...testObject,
      personalData: {
        ...testObject.personalData,
        name: 'McDonnell DC-10',
      },
    });
  }, []);

Also I guess you want to update the property name and no to add the whole object again inside personalData, that is why you need to use ...testObject.personalData

  • Related