Added functional user login

This commit is contained in:
keannu125 2023-02-26 23:50:13 +08:00
parent 352823a329
commit 4caf7479fd
3 changed files with 19 additions and 12 deletions

View file

@ -1,5 +1,7 @@
import axios from "axios";
import { useSelector, useDispatch } from "react-redux";
// Note APIs
export function GetNotes() {
return axios.get("http://localhost:8000/api/v1/notes/").then((response) => {
return response.data;
@ -23,6 +25,8 @@ export function DeleteNote(id: number) {
return axios.delete("http://localhost:8000/api/v1/notes/" + id + "/");
}
// User APIs
export interface user {
username: string;
password: string;
@ -33,7 +37,10 @@ export function UserLogin(user: user) {
.post("http://localhost:8000/api/v1/accounts/token/login/", user)
.then(async (response) => {
localStorage.setItem("token", JSON.stringify(response.data.auth_token));
console.log("Stored: ", JSON.parse(localStorage.getItem("token") || ""));
console.log(
"Login Success! Stored Token: ",
JSON.parse(localStorage.getItem("token") || "")
);
return true;
})
.catch((error) => {

View file

@ -2,7 +2,7 @@ import * as React from "react";
import { Button } from "@mui/material";
import { useNavigate } from "react-router-dom";
import styles from "../../styles";
import { useSelector, useDispatch } from "react-redux";
import { useDispatch, useSelector } from "react-redux";
import { SetLoggedOut } from "../../Features/Redux/Slices/LoginSlice/LoginSlice";
import { UnsetUser } from "../../Features/Redux/Slices/LoggedInUserSlice/LoggedInUserSlice";

View file

@ -5,10 +5,11 @@ import { useNavigate } from "react-router-dom";
import Header from "../../Components/Header/Header";
import { useState } from "react";
import { Button } from "@mui/material";
import { UserLogin, UserInfo } from "../../Components/Api/Api";
import { SetLoggedIn } from "../../Features/Redux/Slices/LoginSlice/LoginSlice";
import { UserInfo, UserLogin } from "../../Components/Api/Api";
import { useSelector, useDispatch } from "react-redux";
import { SetUser } from "../../Features/Redux/Slices/LoggedInUserSlice/LoggedInUserSlice";
import { SetLoggedIn } from "../../Features/Redux/Slices/LoginSlice/LoginSlice";
export default function Login() {
const navigate = useNavigate();
@ -18,7 +19,6 @@ export default function Login() {
password: "",
});
const [error, setError] = useState("");
return (
<div style={styles.background}>
<Header />
@ -51,13 +51,13 @@ export default function Login() {
style={styles.button_green}
variant="contained"
onClick={async () => {
setUser({
username: "",
password: "",
});
if (await UserLogin(user)) {
setUser({
username: "",
password: "",
});
dispatch(SetLoggedIn());
dispatch(SetUser(await UserInfo()));
await dispatch(SetLoggedIn());
await dispatch(SetUser(await UserInfo()));
navigate("/");
} else {
setError("Invalid Login");