Refactor this function to reduce its Cognitive Complexity for if else condition

Viewed 1587

I'm getting error in sonar for cognitive complexity, find my code and attached screenshot for more reference. Please help me to resolve this

 useEffect(() => {
    if (isFocused && isLoggedIn) {
      getProfileData();
    }
    if (isFocused) {
      dispatch(rewardsLandingScreenTracker());
    }
  }, [dispatch, getProfileData, isLoggedIn, isFocused]);

enter image description here

Can someone also update me what will be the solution in case of ternary operator like

  const savedPrice =
    (actualPrice ? getConvertedPrice(actualPrice) : 0) -
    (proPrice ? getConvertedPrice(proPrice) : 0);

enter image description here

1 Answers

You may rewrite it as:

useEffect(() => {
    if (isFocused) {
        if (isLoggedIn) getProfileData();
        dispatch(rewardsLandingScreenTracker());
    }
}, [dispatch, getProfileData, isLoggedIn, isFocused]);

or

useEffect(() => {
    if (!isFocused) return
        
    if (isLoggedIn) getProfileData();
    dispatch(rewardsLandingScreenTracker());
}, [dispatch, getProfileData, isLoggedIn, isFocused]);

The second one may raise lint error on inconsistent return (depends on your linter settings). Then you'll have to add explicit return at the end of the callback function.

Related