in my React component, I pass in a prop called chemicalSignature
. I also have a value that I get from localStorage.
I have a constant called reactionValue
that I want to either hold the value of chemicalSignature
or the value of chemicalVaultValue
.
I want reactionValue
to use the value of chemicalVaultValue
if chemicalSignature
is null or chemicalVaultValue
has a value.
If chemicalVaultValue
is null, then I want it to use chemicalSignature
.
If both chemicalVaultValue
and chemicalSignature
are null, I want it to use a place holder value like, "...Your Chemical String".
Right now, I set the value of reactionValue
using useMemo()
as you can see below.
Is there a way to check 3 conditions using useMemo()
?
The 3 conditions would be:
// if chemicalVaultValue has value and chemicalSignature is null:
if(chemicalVaultValue && !chemicalSignature) {
reactionValue = chemicalVaultValue;
}
// if chemicalVaultValue has a value (we don't care about chemicalSignature at this point)
if(chemicalVaultValue) {
reactionValue = chemicalVaultValue;
}
// if both are null, use a placerholder text value
if(!chemicalVaultValue && !chemicalSignature) {
reactionValue = "...Your Chemical String";
}
I can't figure out how to use this in useMemo().
So far I just have this:
const App = ({ chemicalId, chemicalSignature, chemical }) => {
var chemicalVaultValue = localStorage.getItem(chemicalId);
const reactionValue = useMemo(() => {
return chemicalVaultValue || chemicalSignature;
}, [chemicalId, chemicalSignature]
);
const [chemicalState, setChemicalState] = useState(reactionValue);
Would there be a way to check all 3 conditions inside useMemo()?
Thanks!
first 2 conditions could be merged only in one condition, since chemicalSignature
doesn't have a role in it:
const reactionValue = useMemo(() => {
if(chemicalVaultValue) return chemicalVaultValue;
if(!chemicalVaultValue && !chemicalSignature) return "...Your Chemical String";
}, [chemicalVaultValue, chemicalSignature]
);
fwiw there is another condition !chemicalVaultValue && chemicalSignature
that is not covered. If it should return the placeholder as well you function could be reduced to a ternary operator:
const reactionValue = useMemo(() => {
return chemicalVaultValue ? chemicalVaultValue : "...Your Chemical String";
}, [chemicalVaultValue]
);
There is a simple way with nullish coascaling. You might be able to just use ||
, but this eslint rule Explains why it's better to use ??
.
const reactionValue = useMemo(
() => chemicalVaultValue ?? chemicalSignature ?? '...Your Chemical Strin',
[chemicalId, chemicalSignature]
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.