Search code examples
reactjsreact-hooksreact-componentreact-functional-component

How to call service class method from functional component in react


I have an OIDC client service

export class AuthService {
    public userManager: UserManager;
    private user: any = null;

    constructor() {
        const settings = this.getClientSettings();
        this.userManager = new UserManager(settings);
    }

    public isLoggedIn(): boolean {
        return this.user != null && this.user.access_token && !this.user.expired;
    }

    loadUser() {
        this.userManager.getUser().then((user) => this.user = user);
    }

    public getUser(): Promise<User | null> {
        return this.userManager.getUser().then((user) => this.user = user);
    }

    public login(): Promise<void> {
        return this.userManager.signinRedirect();
    }
}

Functional component

export default function NavMenu() {
    
    useSelector((state: ApplicationState) => state.oidcUser);
    const dispatch = useDispatch();
    const [state, setState] = useState({
        menu: {
            open: true,
            coordinates: undefined
        }
    });
    const onClose = () => {
        setState({
            ...state, menu: {
                open: false,
                coordinates: undefined
            }
        })
    }
    authService: AuthService;
const login = () => {
    authService.startAuthentication(window.location.pathname);
};

    const menuOptions = [
        'Save',
        'Edit',
        'Cut',
        'Copy',
        'Paste',
      ];

    return (<div>
        <TopAppBar>
            <TopAppBarRow>
                <TopAppBarSection align='start'>
                    <TopAppBarTitle>Falcon</TopAppBarTitle>
                </TopAppBarSection>
                <TopAppBarSection align='end' role='toolbar'>
                    <div>
                        {(() => {
                            if (true) {
                                return (
                                    <Button raised type="button" onClick={() => { login }}>Portal</Button>
                                )
                            } else {
                                return (
                                    <Menu
                                        open={state.menu.open}
                                        onClose={onClose}
                                        coordinates={state.menu.coordinates}
                                        onSelected={(index, item) => console.log(index, item)}>
                                        <MenuList>
                                            {menuOptions.map((option : any, index : any) => (
                                                <MenuListItem key={index}>
                                                    <MenuListItemText primaryText={option} />
                                                    {/* You can also use other components from list, which are documented below */}
                                                </MenuListItem>
                                            ))}
                                        </MenuList>
                                    </Menu>
                                )
                            }
                        })()}
                    </div>
                </TopAppBarSection>
            </TopAppBarRow>
        </TopAppBar>
    </div>);
}

Trying to call

authService: AuthService;
    const login = () => {
        authService.startAuthentication(window.location.pathname);
    };

Getting an error Cann't find the name authService

How to call service class method from react functional component.


Solution

  • Here, you could do something like this in your functional component:

    import * as React from "react";    
    import { AuthService } from "./AuthService";
    
    export default function NavMenu() {
      const authService = new AuthService();
    
      const login = () => {
        authService.startAuthentication(window.location.pathname);
      }
    
      return (
        <div className="App">
          <h1>Hello NavMenu</h1>
        </div>
      );
    }
    

    If you have any more questions, would be happy to help!