Sniberb
Sniberb4mo ago

snowberb – 11-30 Mar 28

Imagine that im refactoring a function that does a lot of things. In this case, the handleOnClick of a button. This function has to check for some query requirements and some additional props. Im creating individual functions for the different logics that it needs. My question is, where should I store those functions? In a separate file? What if the functions needs utility functions like a dispatch and some redux-like action functions? In the same component? A very short example: Before
const onSearchClick = async () => {
if (x) {
return;
}

const y = ...;
if (!y) {
...
return;
}

if (z) {
...
return;
}

if (!check1()) {
return;
}

if (!prop1.x) {
...
return;
}

...
};
const onSearchClick = async () => {
if (x) {
return;
}

const y = ...;
if (!y) {
...
return;
}

if (z) {
...
return;
}

if (!check1()) {
return;
}

if (!prop1.x) {
...
return;
}

...
};
After
const onSearchClick = async () => {
if (!checkX()) {
return;
}

if (!checkY()) {
return;
}

if (!checkZ()) {
return;
}

if (!check1()) {
return;
}

if (!check2()) {
return;
}
...
};
const onSearchClick = async () => {
if (!checkX()) {
return;
}

if (!checkY()) {
return;
}

if (!checkZ()) {
return;
}

if (!check1()) {
return;
}

if (!check2()) {
return;
}
...
};
4 Replies
<Alterion.Dev>
<Alterion.Dev>4mo ago
So here's my question : why do you have a single button handling a lot of different concerns? This feels like a great antipattern to stop using, imho
Sniberb
Sniberb4mo ago
Code was already like this, im trying to refactor this the simplest and fastest way If you have a suggestion im listening If these checks are not in the button, where would they be then? This logic must be checked before hitting search, and the button must be enabled I dont think there are a lot of options
<Alterion.Dev>
<Alterion.Dev>4mo ago
where they would be really depends. if this is some sort of state like redux, I'd just make a property in that state that tells me if everything is valid or not, like a derived property using useMemo for example if not, I'd made a function called, I dunno, "canSubmitForm()" which would do all those checks and return a boolean, meaning the actual button click would be a lot cleaner
reactibot
reactibot4mo ago
This thread hasn’t had any activity in 36 hours, so it’s now locked. Threads are closed automatically after 36 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1222870410060894249