Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

332
Vistas
How change setState of object in other object in React?

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

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'
    }}})
about 4 years ago · Juan Pablo Isaza Denunciar

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda