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

160
Vistas
useEffect values append instead of update

I am writing a react script where whenever new transport data comes from backend, it should track it and show it in frontend, but the problem is whenever new values arrive from backend, it appends with old state. I am confused how to solve it.

const transportData = [
  [
    {
      type: "metro",
      icon: MetroIcon,
      sessionCount: 0,
      totalGreenhouseGazes: 0,
    },
    {
      type: "bus",
      icon: AutoBusIcon,
      sessionCount: 0,
      totalGreenhouseGazes: 0,
    },
  ],
  [
    {
      type: "run",
      icon: RunIcon,
      sessionCount: 0,
      totalGreenhouseGazes: 0,
    },
    {
      type: "carpool",
      icon: CarpoolIcon,
      sessionCount: 0,
      totalGreenhouseGazes: 0,
    },
  ],
  
  ];

 const [allTransport, setAllTransport] = React.useState([]); <-- this is coming from backend


    //in the format {bike: {sessionCount: 1, totalGreenhouseGazes: 10}
bus: {sessionCount: 0, totalGreenhouseGazes: 12}}

I want to these allTransprt data to update the above transport data

 const [transport, setTransport] = React.useState(transportData);
 
React.useEffect(() => {
    // find the mode of transport of populate its data correctly
    const keys = Object.keys(allTransport || {});

    transport.map((groupOfMode) => {
      groupOfMode.map((mode) => {
        keys.forEach((key) => {
          if (key === mode.type) {
            mode.sessionCount = allTransport[key]?.sessionCount || 0;
            mode.totalGreenhouseGazes =
              allTransport[key]?.totalGreenhouseGazes || 0;
            mode.totalDistance = allTransport[key]?.totalDistance || 0;
            
          }
        });
      });
    });
  }, [allTransport]);

From my code, the allTransport data comes, updates in transportData and looks like this in frontend when allTransport has all four selected values.

enter image description here

In 2nd iteration, when the allTransport data comes, it displays the previous values of transportData and updates the one selected. Like this: enter image description here

This happened when only the three data were selected. Though the red circle was not the one retrieved from backend, it put the previous value. So I want something that if the value is not retrieved from backend, it should just have original value from transportData.

Any help is appreciated. Thanks!!

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

0

You need to copy the previous state then marge it with new one.

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