Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda