forked from digitallyinduced/thin-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact.js
37 lines (30 loc) · 1.16 KB
/
react.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, { useState, useEffect, useContext } from 'react';
import { getCurrentUserId, ensureIsUser, initAuth } from 'thin-backend/auth.js';
import { useQuerySingleResult, AuthCompletedContext } from 'ihp-datasync/react';
import { query } from 'ihp-datasync';
export function ThinBackend({ children, requireLogin = false }) {
const [authCompleted, setAuthCompleted] = useState(false);
useEffect(() => {
(requireLogin ? ensureIsUser : initAuth)().then(() => setAuthCompleted(true));
}, [])
return React.createElement(AuthCompletedContext.Provider, { value: authCompleted }, children);
}
export function useCurrentUserId() {
const isAuthCompleted = useContext(AuthCompletedContext);
if (!isAuthCompleted) {
return null;
}
return getCurrentUserId();
}
export function useIsLoggedIn() {
const isAuthCompleted = useContext(AuthCompletedContext);
if (!isAuthCompleted) {
return null;
}
return getCurrentUserId() !== null;
}
export function useCurrentUser() {
const userId = useCurrentUserId();
return useQuerySingleResult(query('users').filterWhere('id', userId));
}
export * from 'ihp-datasync/react';