Reactjk
---Example Starter Code (Login Form):---
import { useState } from "react";
import { useNavigate } from "react-router-dom";
function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
// Add validation + API call here
};
return (
<form onSubmit={handleSubmit}> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button type="submit">Login</button> {error && <p>{error}</p>} </form> ); }const handleSubmit = async (e) => {
e.preventDefault();
setError("");
// Validation
if (!email.includes("@")) {
setError("Invalid email");
return;
}
if (password.length < 6) {
setError("Password must be at least 6 characters");
return;
}
// Proceed with API call
};
---Using Fetch API:---
const handleSubmit = async (e) => {
// ... (validation code above)
try {
const response = await fetch("https://api.example.com/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
if (!response.ok) throw new Error("Login failed");
const data = await response.json();
localStorage.setItem("token", data.token); // Store token
navigate("/dashboard"); // Redirect
} catch (err) {
setError(err.message);
}
};
---Using Axios:---
import axios from "axios";
const handleSubmit = async (e) => {
// ... (validation code above)
try {
const response = await axios.post(
"https://api.example.com/login",
{ email, password }
);
localStorage.setItem("token", response.data.token);
navigate("/dashboard");
} catch (err) {
setError(err.response?.data?.message || "Login failed");
}
};
---Mock API Response (for Testing)---
---If you don't have a real API endpoint, mock the response:---
// Mock successful response
const mockApi = {
token: "fake-jwt-token-123",
user: { email }
};
// Use this instead of real API calls for testing:
const data = await new Promise(resolve =>
setTimeout(() => resolve(mockApi), 1000)
);