Define a constant instead of duplicating this literal 3 times sonar
11,266
The message is a little bit confusing but sonar is complaining only about the LoginFailed
string used three times as parameter.
Create a constant as, for example:
const LOGIN_FAILED = 'LoginFailed';
And then use it in all the three calls to displayAlert:
return displayAlert(LOGIN_FAILED);
Author by
Nie Selam
Updated on June 14, 2022Comments
-
Nie Selam almost 2 years
I am wondering how I would refactor the following. Basically, after I get the user information from google, it is validated since a specific domain might be allowed. If it passes that one, we validate the token against a back end api.
Sonar is complaining on the use of return displayAlert('LoginFailed') three times. Given the methods have unique use, I am wondering what could be done to improve it?
import React, {useContext} from 'react'; import {View, Alert} from 'react-native'; import {LocalizationContext} from 'library/localization'; import ServiceAuth from 'services/ServiceAuth'; import {saveLoggedInDetails} from 'library/userInformation'; const MyComponent = (props) => { const {translations} = useContext(LocalizationContext); const displayAlert = (msg) =>{ //translations happen here Alert.alert("Failed", msg) return false; } const validateToken = async (userGoogleInfo) => { const {idToken} = userGoogleInfo; let serviceAuth = ServiceAuth.getInstance(); try { return await serviceAuth.validateT(idToken); } catch (error) { //show alert here return displayAlert('LoginFailed') } }; const authorize = async (userGoogleInfo) => { const allowedDomains = []; let reply = {ok: false}; //check if domain is allowed etc and set to true. if (!reply['ok']) { return displayAlert('InvalidDomain'); } try { const userInfo = await validateToken(userGoogleInfo); if (userInfo) { console.log("okay") } else { return displayAlert('LoginFailed') } } catch (error) { return displayAlert('LoginFailed') } }; return ( <> <View> <Text>Hello</Text> </View> </> ); }; export default MyComponent;
-
Nie Selam almost 4 yearsthanks! that worked. I totally overlooked it. Thanks a bunch.