skip to Main Content
export default function loginvia(loginmethod: string) {
    const [state, setstate] = useState(loginmethod);
    function login() {
        body
    }
    function oauth() {
        body
        login()
    }
    function magic_link() {
       body
       login()
     }
     return eval(state);
}

import loginvia from "./filename";

const authlogin = loginvia("oauth");
authlogin();

hey folks,i need to use child login function as helper function in different login methods and i cant write login function outside main function body because of hooks and mutations i am using. so, i used eval in return to call string as function. so i can import parent function and use whichever login method for login. so, is this right approach to solve this problem or if not then please suggest me one.

2

Answers


  1. Not sure you need state here, instead of eval I would just use a simple object lookup to the methods.

    And since you are using Typescript I would add some typing here to make things a bit nicer.

    eg.

    type LoginMethods = 'oauth' | 'magic_link';
    
    export default function useLoginvia(loginmethod: LoginMethods) {
        function login() {
        }
        function oauth() {
            login()
        }
        function magic_link() {
           login()
        }
        const loginMethods:Record<LoginMethods, () => void> = {
            magic_link,
            oauth
        }
        return loginMethods[loginmethod]
    }
    
    //import loginvia from "./filename";
    
    const authlogin = useLoginvia("oauth");
    authlogin();
    
    Login or Signup to reply.
  2. The use of eval is generally discouraged in JavaScript due to security risks. You can use this approach by defining separate functions for each login method within the component.

    import React, { useState } from "react";
    
    export default function LoginVia({ loginMethod }) {
      const [state, setState] = useState(loginMethod);
    
      const login = () => {
        console.log("Common login logic");
      };
    
      const oauth = () => {
        console.log("OAuth specific logic");
        login();
      };
    
      const magicLink = () => {
        console.log("Magic link specific logic");
        login();
      };
    
      const handleLogin = () => {
        switch (state) {
          case "oauth":
            oauth();
            break;
          case "magic_link":
            magicLink();
            break;
          default:
            console.error("Invalid login method");
        }
      };
    
      handleLogin();
    
      return null;
    }
    
    import LoginVia from "./LoginVia";
    
    const authLogin = <LoginVia loginMethod="oauth" />;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search