From dc3fd4e4741a4d6423283bca26e3213cf957804d Mon Sep 17 00:00:00 2001 From: Guillaume Dorce Date: Fri, 9 Sep 2022 16:53:46 +0200 Subject: [PATCH] display user name in header --- client/src/App.tsx | 13 +++++++---- client/src/components/AppHeader.tsx | 36 ++++++++++++++++++++++++++--- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/client/src/App.tsx b/client/src/App.tsx index 93c6bc5..94c82f2 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -3,6 +3,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import Login from './routes/login'; import Home from './routes/home'; import { checkAuth } from './controllers/Auth'; +import { CookiesProvider } from 'react-cookie'; // Create a client const queryClient = new QueryClient(); @@ -11,11 +12,13 @@ export default () => { return ( - - : } /> - : } /> - - + + + : } /> + : } /> + + + ); diff --git a/client/src/components/AppHeader.tsx b/client/src/components/AppHeader.tsx index 0ae6dff..e165a86 100644 --- a/client/src/components/AppHeader.tsx +++ b/client/src/components/AppHeader.tsx @@ -1,6 +1,33 @@ import logo from '@assets/images/logo.svg'; +import { useQuery } from '@tanstack/react-query'; +import { Cookies, withCookies } from 'react-cookie'; +import { useNavigate } from 'react-router-dom'; + +const getMeInfo = async () => { + const token = new Cookies().get('token'); + const response = await fetch('/api/me', { + method: 'GET', + mode: 'cors', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }, + }); + return response.json(); +}; + + const AppHeader = () => { + const meInfo = useQuery(['me'], getMeInfo, { + onSuccess: (data) => { + return data; + }, + onError: (error) => { + console.error(error); + }, + }); + return (
@@ -12,9 +39,12 @@ const AppHeader = () => { avatar
- John Doe + + {meInfo.isLoading ? '' : meInfo.data ? meInfo.data.firstName + ' ' + meInfo.data.lastName : ''} +
-
@@ -23,4 +53,4 @@ const AppHeader = () => { ); }; -export default AppHeader; +export default withCookies(AppHeader);