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

108
Vistas
Only update one item from ReactJS state items

Problem: I am trying to modify only one item from plan data using this.setState({ planData: { id: plan }}); but by doing so, all my other items become undefined. I found a workaround by adding all other items to my setState, but it doesn't look good at all. Is there a way to only modify a single item from planData without having to set all the other at the same time.

Sample Code:

class Pricing extends Component {
    constructor() {
        super();
        this.state = {
             planData: {
                 id: 3,
                 price: 0,
                 vpnEnabled: false,
                 cloudEnabled: false,
                 cloudSpace: 0
             }
        };
    }

    planHandler(plan) {
        this.setState({ planData: { id: plan }});
    }

    render() {
        <div>
             <button onClick={() => this.planHandler(2)}>Submit</button>
        </div>
    }
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can spread the existing state to maintain the existing values.

planHandler(plan) {
    const data = this.state.planData
    this.setState({ planData: { 
       ...data, 
       id: plan 
    }});
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Access planData from state using this.state.planData

You need the spread operator - ....

planHandler(plan) {
        this.setState({ planData: { ...(this.state.planData),  id: plan }});
    }

Spread breaks open the object keys and properties. Since the above code will lead to id key twice, the one later overrides the first one.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use the spread operator to do so something like

planHandler(plan) {
    this.setState({ planData: {...this.state.planData, id: plan }});
}

This will keep the other values intact while updating the things we need to update

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