Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lecture class 58 #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ import "./App.css";
import { Routes, Route } from "react-router-dom";
import Homepage from "./pages/Homepage";
import PostPage from "./pages/PostPage";
import LoginPage from "./pages/LoginPage";
import NavBar from "./component/NavBar";

export default function App() {
return (
<div>
<NavBar />
<Routes>
{/* more pages to be added here later */}
<Route path="/" element={<Homepage />} />
<Route path="/post/:id" element={<PostPage />} />
<Route path="/login" element={<LoginPage />} />
</Routes>
</div>
);
Expand Down
39 changes: 39 additions & 0 deletions src/component/NavBar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Link } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { getUser } from "../store/auth/selectors";
import { logout } from "../store/auth/slice";

const NavBar = () => {
const user = useSelector(getUser);
const dispatch = useDispatch();

return (
<div
style={{
display: "flex",
justifyContent: "space-between",
paddingRight: 30,
paddingLeft: 30,
backgroundColor: "purple",
}}
>
<Link to="/">
<h2>Coders!</h2>
</Link>
<div style={{ marginTop: 25 }}>
{user ? (
<div style={{ display: "flex" }}>
<h4>Welcome {user.name}!</h4>
<button onClick={() => dispatch(logout())}>logout</button>
</div>
) : (
<Link to="/login">
<button>Login</button>
</Link>
)}
</div>
</div>
);
};

export default NavBar;
56 changes: 56 additions & 0 deletions src/pages/LoginPage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// src/pages/LoginPage.js
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { login } from "../store/auth/thunks";
import { useNavigate } from "react-router-dom";

export default function LoginPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const dispatch = useDispatch();
const navigate = useNavigate();

function handleSubmit(event) {
event.preventDefault();

// Make a POST request
// Create a thunk for this!
dispatch(login(email, password, navigate));

// TODO
console.log("TODO login with:", email, password);
setEmail("");
setPassword("");
}

return (
<div>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<p>
<label>
Email:{" "}
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
</p>
<p>
<label>
Password:{" "}
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
</p>
<p>
<button type="submit">Login</button>
</p>
</form>
</div>
);
}
1 change: 1 addition & 0 deletions src/store/auth/selectors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const getUser = (reduxState) => reduxState.auth.user;
28 changes: 28 additions & 0 deletions src/store/auth/slice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
loading: false,
token: null,
user: null,
};

export const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
startLoading: (state) => {
state.loading = true;
},
saveLoginData: (state, action) => {
state.token = action.payload.token;
state.user = action.payload.user;
},
logout: (state) => {
return { ...initialState };
},
},
});

export const { startLoading, saveLoginData, logout } = authSlice.actions;

export default authSlice.reducer;
35 changes: 35 additions & 0 deletions src/store/auth/thunks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import axios from "axios";
import { saveLoginData, startLoading } from "./slice";

import { API_URL } from "../../config";

export const login =
(email, password, navigate) => async (dispatch, getState) => {
try {
// dispatch => set loading to true
dispatch(startLoading());

// Make POST to /login
const response = axios.post(`${API_URL}/login`, {
email,
password,
});

const token = response.data.jwt;

const profileResponse = axios.get(`${API_URL}/me`, {
headers: {
authorization: `Bearer ${token}`,
},
});

navigate("/");

console.log("me response", profileResponse.data);
// store it in redux => dispatch something.

dispatch(saveLoginData({ token, user: profileResponse.data }));
} catch (e) {
console.log(e.message);
}
};
2 changes: 2 additions & 0 deletions src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
import { configureStore } from "@reduxjs/toolkit";
import feedReducer from "./feed/slice";
import postPageReducer from "./postPage/slice";
import authReducer from "./auth/slice";

const store = configureStore({
reducer: {
feed: feedReducer,
postPage: postPageReducer,
auth: authReducer,
},
});

Expand Down