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:
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();
});
};
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:
Writing a custom hook where I pass the setState methods as parameters. Seems awfully inefficient.
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?