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;
}
...
};
ME
<Maddie> [Evie.Codes][She/Her]46d 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
S
Sniberb46d 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
ME
<Maddie> [Evie.Codes][She/Her]46d 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
UU
Unknown User44d ago