From 8d0b32f8dfe45291426e58f6bf20cffac8dab6e7 Mon Sep 17 00:00:00 2001
From: Joseph Ditton <jditton.atomic@gmail.com>
Date: Tue, 23 Nov 2021 14:04:12 -0700
Subject: adds api, guard, tailwind

---
 client/app.jsx | 47 +++++++++++++++++++++++++++++++----------------
 1 file changed, 31 insertions(+), 16 deletions(-)

(limited to 'client/app.jsx')

diff --git a/client/app.jsx b/client/app.jsx
index 6414fad..a7de3cf 100644
--- a/client/app.jsx
+++ b/client/app.jsx
@@ -1,25 +1,40 @@
-import { useReducer } from 'react';
+import { useState, useEffect } from 'react';
 import { HashRouter } from 'react-router-dom';
 import { Router } from './components/router';
-import { SettingsContext } from './utils/settings_context';
+import { ApiContext } from './utils/api_context';
+import { AuthContext } from './utils/auth_context';
+import { useApi } from './utils/use_api';
+import { useJwtRefresh } from './utils/use_jwt_refresh';
+import './app.css';
 
-const settingsReducer = (state, action) => {
-  switch (action.type) {
-    case 'update': {
-      return { ...state, ...action.payload };
+export const App = () => {
+  const [authToken, setAuthToken] = useState(null);
+  const [loading, setLoading] = useState(true);
+
+  // Refresh the jwt token automatically
+  useJwtRefresh(authToken, setAuthToken);
+
+  // api instance
+  const api = useApi(authToken);
+
+  // get initial jwt using refresh token
+  useEffect(async () => {
+    const result = await api.get('/refresh_token');
+    if (result.token) {
+      setAuthToken(result.token);
     }
-  }
-  return state;
-};
+    setLoading(false);
+  }, []);
 
-export const App = () => {
-  const [settings, dispatch] = useReducer(settingsReducer, window.SETTINGS);
+  if (loading) return null;
 
   return (
-    <SettingsContext.Provider value={[settings, dispatch]}>
-      <HashRouter>
-        <Router />
-      </HashRouter>
-    </SettingsContext.Provider>
+    <AuthContext.Provider value={[authToken, setAuthToken]}>
+      <ApiContext.Provider value={api}>
+        <HashRouter>
+          <Router />
+        </HashRouter>
+      </ApiContext.Provider>
+    </AuthContext.Provider>
   );
 };
-- 
cgit v1.2.3-70-g09d2

