Added Redux states for login status and user logged in

This commit is contained in:
keannu125 2023-02-26 23:21:52 +08:00
parent 61bdec145b
commit 352823a329
6 changed files with 90 additions and 45 deletions

View file

@ -1,5 +1,5 @@
import axios from "axios"; import axios from "axios";
import { useSelector, useDispatch } from "react-redux";
export function GetNotes() { export function GetNotes() {
return axios.get("http://localhost:8000/api/v1/notes/").then((response) => { return axios.get("http://localhost:8000/api/v1/notes/").then((response) => {
return response.data; return response.data;
@ -34,7 +34,6 @@ export function UserLogin(user: user) {
.then(async (response) => { .then(async (response) => {
localStorage.setItem("token", JSON.stringify(response.data.auth_token)); localStorage.setItem("token", JSON.stringify(response.data.auth_token));
console.log("Stored: ", JSON.parse(localStorage.getItem("token") || "")); console.log("Stored: ", JSON.parse(localStorage.getItem("token") || ""));
StoreUser();
return true; return true;
}) })
.catch((error) => { .catch((error) => {
@ -43,23 +42,6 @@ export function UserLogin(user: user) {
}); });
} }
export function StoreUser() {
const token = JSON.parse(localStorage.getItem("token") || "");
return axios
.get("http://localhost:8000/api/v1/accounts/users/me/", {
headers: {
Authorization: "Token " + token,
},
})
.then((response) => {
localStorage.setItem("user", JSON.stringify(response.data));
})
.catch((error) => {
console.log("Error in storing user data");
console.log(error);
});
}
export function UserInfo() { export function UserInfo() {
const token = JSON.parse(localStorage.getItem("token") || ""); const token = JSON.parse(localStorage.getItem("token") || "");
return axios return axios
@ -76,20 +58,3 @@ export function UserInfo() {
console.log(error); console.log(error);
}); });
} }
export function GetUsername() {
const token = JSON.parse(localStorage.getItem("token") || "");
return axios
.get("http://localhost:8000/api/v1/accounts/users/me/", {
headers: {
Authorization: "Token " + token,
},
})
.then((response) => {
return response.data;
})
.catch((error) => {
console.log("Error in fetching user data");
console.log(error);
});
}

View file

@ -1,15 +1,27 @@
import * as React from "react"; import * as React from "react";
import { useState } from "react";
import { Button } from "@mui/material"; import { Button } from "@mui/material";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import styles from "../../styles"; import styles from "../../styles";
import { GetUsername, UserInfo } from "../Api/Api"; import { useSelector, useDispatch } from "react-redux";
import { SetLoggedOut } from "../../Features/Redux/Slices/LoginSlice/LoginSlice";
import { UnsetUser } from "../../Features/Redux/Slices/LoggedInUserSlice/LoggedInUserSlice";
export interface user {
LoggedInUser: {
value: {
email: string;
id: number;
username: string;
};
};
}
export default function LoginButton() { export default function LoginButton() {
const [logged_in, setLoggedIn] = useState(false); const dispatch = useDispatch();
const [user, setUser] = useState( const logged_in = useSelector(
JSON.parse(localStorage.getItem("user") || "").username (state: { Login: { logged_in: boolean } }) => state.Login.logged_in
); );
const logged_in_user = useSelector((state: user) => state.LoggedInUser.value);
const navigate = useNavigate(); const navigate = useNavigate();
if (!logged_in) { if (!logged_in) {
return ( return (
@ -30,13 +42,16 @@ export default function LoginButton() {
} }
return ( return (
<div style={styles.flex_row}> <div style={styles.flex_row}>
<p style={styles.text_small}>Logged in as {user}</p> <p style={styles.text_small}>Logged in as {logged_in_user.username}</p>
<div style={{ margin: 4 }} /> <div style={{ margin: 4 }} />
<Button <Button
style={styles.button_red} style={styles.button_red}
variant="contained" variant="contained"
onClick={() => { onClick={() => {
setLoggedIn(false); console.log("Logged out...");
dispatch(SetLoggedOut());
dispatch(UnsetUser());
localStorage.setItem("token", "");
}} }}
> >
Logout Logout

View file

@ -0,0 +1,33 @@
import { createSlice } from "@reduxjs/toolkit";
export const LoggedInUserSlice = createSlice({
name: "Login",
initialState: {
value: {
email: "",
id: 0,
username: "",
},
},
reducers: {
SetUser: (state, action) => {
state.value = {
email: action.payload.email,
id: action.payload.id,
username: action.payload.username,
};
},
UnsetUser: (state) => {
state.value = {
email: "",
id: 0,
username: "",
};
},
},
});
// Action creators are generated for each case reducer function
export const { SetUser, UnsetUser } = LoggedInUserSlice.actions;
export default LoggedInUserSlice.reducer;

View file

@ -0,0 +1,21 @@
import { createSlice } from "@reduxjs/toolkit";
export const LoginSlice = createSlice({
name: "Login",
initialState: {
logged_in: false,
},
reducers: {
SetLoggedIn: (state) => {
state.logged_in = !state.logged_in;
},
SetLoggedOut: (state) => {
state.logged_in = !state.logged_in;
},
},
});
// Action creators are generated for each case reducer function
export const { SetLoggedIn, SetLoggedOut } = LoginSlice.actions;
export default LoginSlice.reducer;

View file

@ -1,5 +1,10 @@
import { configureStore } from "@reduxjs/toolkit"; import { configureStore } from "@reduxjs/toolkit";
import LoginReducer from "../Slices/LoginSlice/LoginSlice";
import LoggedInUserReucer from "../Slices/LoggedInUserSlice/LoggedInUserSlice";
export default configureStore({ export default configureStore({
reducer: {}, reducer: {
Login: LoginReducer,
LoggedInUser: LoggedInUserReucer,
},
}); });

View file

@ -5,10 +5,14 @@ import { useNavigate } from "react-router-dom";
import Header from "../../Components/Header/Header"; import Header from "../../Components/Header/Header";
import { useState } from "react"; import { useState } from "react";
import { Button } from "@mui/material"; import { Button } from "@mui/material";
import { UserLogin } from "../../Components/Api/Api"; import { UserLogin, UserInfo } from "../../Components/Api/Api";
import { SetLoggedIn } from "../../Features/Redux/Slices/LoginSlice/LoginSlice";
import { useSelector, useDispatch } from "react-redux";
import { SetUser } from "../../Features/Redux/Slices/LoggedInUserSlice/LoggedInUserSlice";
export default function Login() { export default function Login() {
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch();
const [user, setUser] = useState({ const [user, setUser] = useState({
username: "", username: "",
password: "", password: "",
@ -52,6 +56,8 @@ export default function Login() {
username: "", username: "",
password: "", password: "",
}); });
dispatch(SetLoggedIn());
dispatch(SetUser(await UserInfo()));
navigate("/"); navigate("/");
} else { } else {
setError("Invalid Login"); setError("Invalid Login");