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

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

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 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