Implement local storage handling with react hooks and also API requests with fetch
This commit is contained in:
parent
21c5c3b58f
commit
f09d7f1eb2
12
src/App.tsx
12
src/App.tsx
|
|
@ -8,7 +8,19 @@ import Home from "./pages/Home.tsx";
|
||||||
import Login from "./pages/Login.tsx";
|
import Login from "./pages/Login.tsx";
|
||||||
import About from "./pages/About.tsx";
|
import About from "./pages/About.tsx";
|
||||||
|
|
||||||
|
import useLocalStorage from "./components/useLocalStorage.ts";
|
||||||
|
|
||||||
export default function App() {
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
|
|
|
||||||
|
|
@ -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];
|
||||||
|
}
|
||||||
|
|
@ -14,7 +14,18 @@ export default function Login() {
|
||||||
formEvent.preventDefault();
|
formEvent.preventDefault();
|
||||||
|
|
||||||
const formData = new FormData(formEvent.target);
|
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 (
|
return (
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue