0

I've created a state of objects in React, but I need to increase an other object into the same state. However, i can't use the setState() property because its causes 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?

S.Marx
  • 977
  • 10
  • 14

2 Answers2

0

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'
    }}})
Daniel M
  • 133
  • 3
  • 9
0

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

S.Marx
  • 977
  • 10
  • 14