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

107
Vistas
There is a problem with the delete function of the react component implemented through the map method

I am developing using react. It is in the process of fetching the information contained in the db and displaying it on the web page through the map method. If you delete one piece of information using onclick or the onClose method provided by antd, the info is also deleted from the db. in the db, the function worked successfully. but the information at the bottom is deleted, not the deleted information in the web page. If I refresh website, it is displayed normally, but I don't want to use the window reload function. I wonder why this is happening and what is the solution. thank you!

AlertPage

import React, { useState } from "react";
import useSWR from "swr";
import axios from "axios";
import AlertComponent from "./Sections/AlertComponent";

const fetcher = async (url) =>
  await axios.get(url).then((response) => JSON.parse(response.data.alerts));

function AlertPage() {
  const { data = [], error } = useSWR("/api/streaming/getAlerts", fetcher, {
    refreshInterval: 1000,
  });

  const onClose = (data) => {
    axios.post(`/api/streaming/removeAlerts/${data._id.$oid}`).then(() => {
      console.log(`${data._id.$oid} deleted`);
    });
  };

  const renderAlerts = data.map((alert, index) => {
    return (
      <div key={index}>
        <AlertComponent alert={alert} index={index} onClose={onClose} />
      </div>
    );
  });

  if (error) return <div>failed to load</div>;
  if (data === []) return <div>loading...</div>;

  return <div>{renderAlerts}</div>;
}

export default AlertPage;

AlertComponent

import React, { useState } from "react";
import { Alert } from "antd";
import Marquee from "react-fast-marquee";

function AlertComponent(props) {
  const [alert, setalert] = useState(props.alert);
  const [index, setindex] = useState(props.index);

  return (
    <div
      className="alert"
      key={index}
      style={{ display: "flex" }}
      onClick={() => {
        props.onClose(alert);
      }}
    >
      <Alert
        message={`${alert.data.timestamp.$date.substr(0, 19)}`}
        description={
          <Marquee pauseOnHover speed={40} gradient={false}>
            {`<${alert.data.location}> <${alert.data.name}> <${alert.data.contents}> detected`}
          </Marquee>
        }
        banner
      />
    </div>
  );
}

export default AlertComponent;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This could be happening due the local cache maintained by swr and since you're not refetching the data after the deletion the changes are not reflected in the DOM.

One options is to trigger a manual refetch to retrieve the most up-to-date data. We could achieve that by changing the following lines:

const { data = [], error, mutate } = useSWR("/api/streaming/getAlerts", fetcher, {
 refreshInterval: 1000
});

...

 axios.post(`/api/streaming/removeAlerts/${data._id.$oid}`).then(() => {
  mutate("/api/streaming/getAlerts");
 });

another approach would be to rely on the optimistic update strategy from swr, there is an example here

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