@reactivers/hooks Github link@reactivers/hooks NPM link

useAuth

Introduction

  • useAuth manages your application's user info and authorization.
  • It allows login or logout of your users and you can track easily logged in status.
  • You can use useAuth to hide your no public components.
const { 
    token,
    isLoggedIn,
    login,
    logout 
} = useAuth();

Getting Started

  • You need to import useAuth and AuthProvider.
  • You need to wrap AuthProvider component with LocalStorageProvider because AuthProvider uses useLocalStorage to save token.

From Collection

import { useAuth, AuthProvider, LocalStorageProvider } from "@reactivers/hooks";

From Packages

import { useAuth, AuthProvider } from "@reactivers/use-auth";
import { LocalStorageProvider } from "@reactivers/use-local-storage";

Interfaces

Provider

interface AuthProviderProps {
	
	// onLogin function saves the token to this key
	localStorageTokenKeyName?: string;
	
	// onLogin function reads the token by this key
	authTokenKeyName?: string;
	
	// Initially reads token from local storage.
	initialCheckToken?: boolean;
	
	// User info data.
	user?: UserInfo;
	
	//Call this when a user logged in successfully
	onLogin?: (info: UserInfo) => void;
	
	//Call this when a user want to log out
    onLogout?: () => void;
}

interface  UserInfo {
	
    username?: string;
    token?: string;

	//Sets true when onLogin function called
    isLoggedIn: boolean;

	//Any data for user
    userInfo?: any;
}

Hook


interface IUseAuth {

	//For update token
    setToken: (token: string) => void,

	//Make user logged in
    login: (data: any) => void,
	
	//Make user logged out
    logout: () => void,

	//Sets user info
    setUser: (user: UserInfo) => void,

	//User info
    user: UserInfo,

	//Updates when login function called
    isLoggedIn: boolean;

	//Active token for user
    token: string

}

Example

Example Preview - CodeSandbox