Application Android et IOS pour l'amicale des élèves https://play.google.com/store/apps/details?id=fr.amicaleinsat.application
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

loginContext.ts 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import React, { useContext } from 'react';
  2. import { apiRequest } from '../utils/WebData';
  3. export type LoginContextType = {
  4. token: string | undefined;
  5. setLogin: (token: string | undefined) => void;
  6. };
  7. export const LoginContext = React.createContext<LoginContextType>({
  8. token: undefined,
  9. setLogin: () => undefined,
  10. });
  11. /**
  12. * Hook used to retrieve the user token and puid.
  13. * @returns Login context with token and puid to undefined if user is not logged in
  14. */
  15. export function useLogin() {
  16. return useContext(LoginContext);
  17. }
  18. /**
  19. * Checks if the user is connected
  20. * @returns True if the user is connected
  21. */
  22. export function useLoginState() {
  23. const { token } = useLogin();
  24. return token !== undefined;
  25. }
  26. /**
  27. * Gets the current user token.
  28. * @returns The token, or empty string if the user is not logged in
  29. */
  30. export function useLoginToken() {
  31. const { token } = useLogin();
  32. return token ? token : '';
  33. }
  34. export function useAuthenticatedRequest<T>(
  35. path: string,
  36. params?: { [key: string]: any }
  37. ) {
  38. const token = useLoginToken();
  39. return () => apiRequest<T>(path, 'POST', params, token);
  40. }