Skip to content

API Reference

Marcel edited this page Sep 7, 2023 · 2 revisions

API Reference

In this section, you'll find details about the available methods and hooks provided by React Native Laravel Sanctum for integrating Laravel Sanctum authentication into your React Native app.

useAuth

General

The useAuth hook is the primary interface for authentication and user management.

API

Method Description Type
login(email, password, deviceName) Logs in a user with the provided email, password, and device name. Returns true if the login is successful, false otherwise. Function
logout() Logs out the currently authenticated user. Returns true if the logout is successful, false otherwise. Function
updateUser() Updates the user information. Returns the user object if successful, or null if no user is logged in. Function
getToken() Retrieves the authentication token of the currently authenticated user. Returns the token if available, or null if no user is logged in. Function
currentUser Variable containing the user object of the currently authenticated user. It's null if no user is logged in. Object or null
isAuthenticated Boolean variable indicating whether a user is authenticated (true) or not (false). Boolean
setUserIsAuthenticated(userIsAuthenticated) Function to manually set the authentication status of the user. Pass true to authenticate or false to log out. Function

AuthProvider

General

The AuthProvider is a higher-level component that provides authentication configuration to your app.

API

Property Description Type
config An object containing the configuration for authentication. Must include loginUrl, logoutUrl, and userUrl. Object
children The child components wrapped by AuthProvider. ReactNode

Example

import { useAuth, AuthProvider } from '[Your Project Name]';

function MyComponent() {
  const { login, logout, updateUser, getToken, currentUser, isAuthenticated } = useAuth();

  // Example usage of methods and variables:
  const handleLogin = async () => {
    const loggedIn = await login('[email protected]', 'password', 'Device-1');
    if (loggedIn) {
      const user = await updateUser();
      console.log('Logged in user:', user);
    }
  };

  const handleLogout = async () => {
    const loggedOut = await logout();
    if (loggedOut) {
      console.log('User logged out.');
    }
  };

  return (
    <div>
      <button onClick={handleLogin}>Login</button>
      <button onClick={handleLogout}>Logout</button>
      {isAuthenticated && <p>Welcome, {currentUser.name}!</p>}
    </div>
  );
}

function MyApp() {
  const config = {
    loginUrl: 'http://example.com/api/sanctum/token',
    logoutUrl: 'http://example.com/api/logout',
    userUrl: 'http://example.com/api/user'
  };

  return (
    <AuthProvider config={config}>
      <MyComponent />
    </AuthProvider>
  );
}
Clone this wiki locally