Implement local storage handling with react hooks and also API requests with fetch

This commit is contained in:
Curt Spark 2024-04-16 17:38:12 +01:00
parent 21c5c3b58f
commit f09d7f1eb2
3 changed files with 42 additions and 1 deletions

View File

@ -8,7 +8,19 @@ import Home from "./pages/Home.tsx";
import Login from "./pages/Login.tsx";
import About from "./pages/About.tsx";
import useLocalStorage from "./components/useLocalStorage.ts";
export default function App() {
const [usernameValue, setUsernameValue, deleteUsernameValue] =
useLocalStorage("username");
if (localStorage.getItem("username") === null) {
console.log("Username does not exist, creating!");
} else {
console.log("Username does exist!");
console.log(usernameValue);
}
return (
<>
<BrowserRouter>

View File

@ -0,0 +1,18 @@
import { useState, useEffect } from "react";
export default function useLocalStorage(itemName: str) {
const getItemName = localStorage.getItem(itemName);
const [itemValue, setItemValue] = useState(
getItemName === null ? "" : getItemName,
);
useEffect(() => {
localStorage.setItem(itemName, itemValue);
}, [itemValue]);
const deleteItemValue = () => {
localStorage.removeItem(itemName);
};
return [itemValue, setItemValue, deleteItemValue];
}

View File

@ -14,7 +14,18 @@ export default function Login() {
formEvent.preventDefault();
const formData = new FormData(formEvent.target);
console.log(formData);
fetch("http://127.0.0.1:8000/api", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(Object.fromEntries(formData)),
})
.then((response) => response.json())
.then((responseParsed: Object) => {
console.log(responseParsed);
});
}
return (