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

113
Visualizações
Reduce duplicated blocks in a React project

I'm optimizing my React project according to Sonarcloud results. It's in a pretty good state, however I'm getting a high duplication score (20.5%). When I examine it, I see that there are indeed recurring code blocks in different files. The problem is, these blocks are being used to locally set states after successful API calls. Here are a couple of examples:

  1. DefaultCategory.tsx:
const handleUpdate = () => {

let copyCategories = JSON.parse(JSON.stringify(categories));

copyCategories.map((c) =>
  Object.assign({}, c, { url: encodeURIComponent(c.url) })
);

setDisabledButton(true);

apiCall(path, copyCategories)
  .execute()
  .then((_r) => {
    setDisabledButton(false);
    setSuccess(true);
  })
  .catch((_e) => {
    handleError();
  });
};

  1. DetailedCategory.tsx:
const handleUpdate = () => {

    let copyCategories = JSON.parse(JSON.stringify(categories));

    copyCategories.map((c) =>
      Object.assign({}, c, { url: encodeURIComponent(c.url) })
    );

    setDisabledButton(true);

    apiCall(path, copyCategories)
      .execute()
      .then((_r) => {
        setDisabledButton(false);
        setSuccess(true);
      })
      .catch((_e) => {
        handleError();
      });
  };

I'm not sure how to reduce these blocks to a single hook or a function since I set states in them. I don't want to move the components to a single component since they each have different behaviors, and it would become very complicated and unmaintainable.

I have considered:

  1. Writing a custom hook where I pass the setState methods as parameters. Seems awfully inefficient.

  2. Changing the names of duplicated states and functions. This would probably affect the Sonarcloud score but is there an actual best practice for this situation?

about 4 years ago · Juan Pablo Isaza
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