From 941a48425219446c1a23fc9610875ad37b3cc9e0 Mon Sep 17 00:00:00 2001 From: felixtanhm Date: Wed, 8 May 2024 14:40:55 +0800 Subject: [PATCH] feat: user context --- .../client/src/App.jsx | 35 ++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/full-stack-javascript/21-inventory-application/client/src/App.jsx b/full-stack-javascript/21-inventory-application/client/src/App.jsx index 494df82..761d5f5 100644 --- a/full-stack-javascript/21-inventory-application/client/src/App.jsx +++ b/full-stack-javascript/21-inventory-application/client/src/App.jsx @@ -3,6 +3,7 @@ import { createContext, useState } from "react"; import NavBar from "./components/Nav"; export const DarkModeContext = createContext(); +export const UserContext = createContext(); function App() { const urlPath = useLocation().pathname.split("/")[1]; @@ -10,14 +11,40 @@ function App() { const [darkMode, setDarkMode] = useState( window.matchMedia("(prefers-color-scheme: dark)").matches, ); + const [user, setUser] = useState(null); + + async function fetchUser() { + try { + const response = await fetch(`http://localhost:3000/users`); + + if (!response.ok) { + let errorMessage = `Failed to fetch data. Status: ${response.status}`; + if (response.statusText) { + errorMessage += `, Message: ${response.statusText}`; + } + throw new Error(errorMessage); + } + + const result = await response.json(); + setUser(result); + } catch (error) { + console.log(error); + } + } + + if (!user) { + fetchUser(); + } darkMode ? root.classList.add("dark") : root.classList.remove("dark"); return ( - - - - + + + + + + ); }