I have the following useEffect
I want to refactor it, removing all these else if
lines
See the code
useEffect(() => {
if(country === "WW") {
setIsDisable(true);
} else if (country === "GB") {
setIsDisable(false);
} else if (country === "DE") {
setIsDisable(false);
} else if (country === "FR") {
setIsDisable(false);
} else if (country === "BR") {
setIsDisable(false);
} else if (country === "US") {
setIsDisable(false);
} else if (country === "IT") {
setIsDisable(false);
} else if (country === "US") {
setIsDisable(false);
} else if (country === "ES") {
setIsDisable(false);
} else if (country === "MX") {
setIsDisable(false);
}
}, [country]);
As you can see the country: GB
, DE
, FR
, BR
, US
, IT
, US
, ES
and MX
sharing the same setIsDisable(false)
How would you write in 1 line of code whitout repeating the same else if
?
CodePudding user response:
useEffect(() => {
setIsDisable(country === "WW");
}, [country]);
if you want to validate
useEffect(() => {
if (country === "WW")
setIsDisable(true);
else if (["GB", "DE", "FR", "BR", "US", "IT", "ES", "MX"].includes(country))
setIsDisable(false);
}, [country]);