I have to dispatch either the selectedMovie id or the selectedSerie id to redux. I am trying to make a condition. This is what I did now, I added a || operator but I don't quite know if that is possible.
useEffect(() => {
if (isModalVisible) {
if (Array.isArray(dataToSync) && dataToSync.length > 0) {
dataToSync?.forEach((el) =>
dispatch(syncToServer(language, el, SelectedMovie[0]?.id ||
SelectedSerie?.id))
);
}
}
}, [dispatch, language, isModalVisible]);
Yes, use of || is very much possible. When you use The logical OR ( || ) operator, if the first evaluation of the first operand is false, the second operand is evaluated.
var a = (val) => console.log(val, "val")
x = {}
var e = 'e';
a(x?.ele || e);
a(x?.ele ? x?.ele : e);
Solution 2: ??
Nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
dispatch(syncToServer(language, el, SelectedMovie[0]?.id ?? SelectedSerie?.id))
Solution 3: ? :
Another way would be to use a ? : operator.
dispatch(syncToServer(language, el, SelectedMovie[0]?.id ? SelectedMovie[0].id : SelectedSerie?.id))