Client will now login immediately after registration
This commit is contained in:
+42
-11
@@ -1,6 +1,8 @@
|
||||
import React, { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import config from "../config";
|
||||
import { useAuth } from "../AuthContext";
|
||||
|
||||
|
||||
const styles = {
|
||||
form: {
|
||||
@@ -45,6 +47,8 @@ const styles = {
|
||||
};
|
||||
|
||||
const Register = () => {
|
||||
const { login } = useAuth();
|
||||
|
||||
const [form, setForm] = useState({
|
||||
username: "",
|
||||
email: "",
|
||||
@@ -60,27 +64,54 @@ const Register = () => {
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const payload = {
|
||||
username: form.username,
|
||||
password: form.password,
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch(`${config.apiBaseUrl}/api/Auth/register`, {
|
||||
// Step 1: Register the user
|
||||
const registerRes = await fetch(
|
||||
`${config.apiBaseUrl}/api/Auth/register`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
}
|
||||
);
|
||||
|
||||
if (!registerRes.ok) {
|
||||
const errorData = await registerRes.json();
|
||||
throw new Error(errorData.message || "Registration failed");
|
||||
}
|
||||
|
||||
// Consume body even if empty to ensure flush
|
||||
await registerRes.text(); // <-- this is the key to making chaining clean
|
||||
|
||||
// Step 2: Immediately login
|
||||
const loginRes = await fetch(`${config.apiBaseUrl}/api/Auth/login`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: form.username,
|
||||
email: form.email,
|
||||
password: form.password,
|
||||
}),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.message || "Registration failed");
|
||||
if (!loginRes.ok) {
|
||||
throw new Error("Registration succeeded but login failed");
|
||||
}
|
||||
|
||||
navigate("/login");
|
||||
const loginData = await loginRes.json();
|
||||
login(loginData.accessToken);
|
||||
|
||||
localStorage.setItem("token", loginData.accessToken);
|
||||
localStorage.setItem("role", loginData.role);
|
||||
|
||||
navigate("/dashboard");
|
||||
} catch (err) {
|
||||
console.error("Register error:", err);
|
||||
console.error("Register/login error:", err);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user