Sure, I can help modify your Next.js project files to interface with the backend API you've provided. Below are the updated versions of your index.tsx, login.tsx, and register.tsx files. These modifications include handling form submissions, making API requests to the backend endpoints, managing JWT tokens, and updating the components to reflect the backend data.
Note: Ensure that your backend is accessible, and adjust the API URLs accordingly if needed.
index.tsx
import UserAddReport from "@/components/maps/UserAddReport";
import UserIcon from "@/components/user/UserIcon";
import { Inter } from 'next/font/google'
import dynamic from 'next/dynamic';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
const GoogleMapParent = dynamic(() => import('@/components/maps/GoogleMap'), {
ssr: false
});
const inter = Inter({ subsets: ['latin'] })
export default function Home() {
const [reports, setReports] = useState([]);
const router = useRouter();
useEffect(() => {
const fetchReports = async () => {
const token = localStorage.getItem('token');
if (!token) {
// Redirect to login if not authenticated
router.push('/login');
return;
}
try {
const response = await fetch('/api/v1/report/all', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (response.ok) {
const data = await response.json();
setReports(data);
} else if (response.status === 401) {
// Token might have expired or is invalid
localStorage.removeItem('token');
router.push('/login');
} else {
console.error('Failed to fetch reports');
}
} catch (error) {
console.error('An error occurred:', error);
}
};
fetchReports();
}, [router]);
return (
<div>
<style jsx global>{`
html {
font-family: ${inter.style.fontFamily};
}
`}</style>
<GoogleMapParent reports={reports} />
<div className="absolute top-0 left-0 w-full">
<div className="p-4 w-full flex">
<UserIcon />
</div>
</div>
<div className="absolute bottom-0 left-0 w-full">
<div className="p-4 pb-8 lg:p-16 lg:px-28 w-full flex justify-end">
<UserAddReport />
</div>
</div>
</div>
);
}
Changes Made:
- Import Statements: Added
useEffect, useState, and useRouter to manage state and routing.
- State Management: Initialized
reports state to store disaster reports fetched from the backend.
- Authentication Check: In the
useEffect hook, checked for the presence of a JWT token in localStorage. If not present, redirected the user to the login page.
- Fetching Reports: Made a GET request to
/api/v1/report/all with the Authorization header containing the JWT token.
- Error Handling: Handled cases where the token is invalid or expired by removing it from
localStorage and redirecting to the login page.
- Passing Data to Map: Passed the
reports data to the GoogleMapParent component to display on the map.
login.tsx
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import Link from "next/link";
import { useRouter } from 'next/router';
function Login() {
const [username, setUsername] = React.useState('');
const [password, setPassword] = React.useState('');
const router = useRouter();
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('/api/v1/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
if (response.ok) {
const data = await response.json();
// Assume data contains the JWT token
const token = data.token;
// Store the token in localStorage
localStorage.setItem('token', token);
// Redirect to the main page
router.push('/');
} else {
// Handle errors
const errorData = await response.json();
console.error('Login failed:', errorData);
alert('Prijava nije uspjela: ' + (errorData.message || 'Nepoznata greška'));
}
} catch (error) {
console.error('An error occurred:', error);
alert('Došlo je do pogreške prilikom prijave.');
}
};
return (
<div className="w-full h-screen flex items-center justify-center p-4">
<Card className="max-w-[350px] w-full">
<CardHeader>
<CardTitle className="text-3xl">Prijava</CardTitle>
<CardDescription>
Prijavi se na svoj korisnički račun ili se registriraj ovdje.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit}>
<div className="grid w-full items-center gap-4">
<div className="flex flex-col space-y-1.5">
<Input
id="username"
type="text"
placeholder="Korisničko ime"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="flex flex-col space-y-1.5">
<Input
id="password"
type="password"
placeholder="Šifra"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<div className="w-full pt-4">
<Button className="w-full" type="submit">
Prijava
</Button>
</div>
</form>
<div className="pt-4">
<p className="text-sm text-center">
Nemate korisnički račun?{" "}
<Link href="/register" className="text-blue-500">
Registriraj se
</Link>
</p>
</div>
</CardContent>
<CardFooter className="flex justify-between">
<Link href="/" className="w-full">
<Button className="w-full" variant={"outline"}>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Google_%22G%22_logo.svg/768px-Google_%22G%22_logo.svg.png"
className="w-6 h-6 mr-2"
alt="google logo"
/>
Prijava s Googleom
</Button>
</Link>
</CardFooter>
</Card>
</div>
);
}
export default Login;
Changes Made:
- State Management: Used
useState to manage username and password inputs.
- Form Handling: Added
onSubmit handler handleSubmit to process form submission.
- API Request: Made a POST request to
/api/v1/user/login with the username and password.
- Token Storage: Stored the received JWT token in
localStorage for future authenticated requests.
- Routing: Used
useRouter from Next.js to redirect to the main page upon successful login.
- Error Handling: Added error handling for unsuccessful login attempts and displayed appropriate messages.
- Input Updates: Changed the email input to username as per the backend API requirements.
register.tsx
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import Link from "next/link";
import { useRouter } from 'next/router';
function Register() {
const [username, setUsername] = React.useState('');
const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState('');
const [repeatPassword, setRepeatPassword] = React.useState('');
const router = useRouter();
const handleSubmit = async (e) => {
e.preventDefault();
if (password !== repeatPassword) {
alert('Lozinke se ne podudaraju');
return;
}
try {
const response = await fetch('/api/v1/user/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password, email }),
});
if (response.ok) {
// Optionally log in the user automatically
// Redirect to login page
router.push('/login');
} else {
// Handle errors
const errorData = await response.json();
console.error('Registration failed:', errorData);
alert('Registracija nije uspjela: ' + (errorData.message || 'Nepoznata greška'));
}
} catch (error) {
console.error('An error occurred:', error);
alert('Došlo je do pogreške prilikom registracije.');
}
};
return (
<div className="w-full h-screen flex items-center justify-center p-4">
<Card className="max-w-[350px] w-full">
<CardHeader>
<CardTitle className="text-3xl">Registracija</CardTitle>
<CardDescription>
Registriraj se za novi korisnički račun.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit}>
<div className="grid w-full items-center gap-4">
<div className="flex flex-col space-y-1.5">
<Input
id="username"
placeholder="Korisničko ime"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="flex flex-col space-y-1.5">
<Input
id="email"
type="email"
placeholder="Vaš email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="flex flex-col space-y-1.5">
<Input
id="password"
type="password"
placeholder="Vaša šifra"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="flex flex-col space-y-1.5">
<Input
id="repeat_password"
type="password"
placeholder="Ponovite šifru"
value={repeatPassword}
onChange={(e) => setRepeatPassword(e.target.value)}
/>
</div>
</div>
<div className="w-full pt-4">
<Button className="w-full" type="submit">
Registracija
</Button>
</div>
</form>
<div className="pt-4">
<p className="text-sm text-center">
Već imate račun?{" "}
<Link href="/login" className="text-blue-500">
Prijavite se
</Link>
</p>
</div>
</CardContent>
<CardFooter className="flex justify-between">
<Link href="/" className="w-full">
<Button className="w-full" variant={"outline"}>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Google_%22G%22_logo.svg/768px-Google_%22G%22_logo.svg.png"
className="w-6 h-6 mr-2"
alt="google logo"
/>
Registracija s Googleom
</Button>
</Link>
</CardFooter>
</Card>
</div>
);
}
export default Register;
Changes Made:
- Component Renaming: Changed the component name from
Login to Register.
- State Management: Used
useState to manage username, email, password, and repeatPassword inputs.
- Form Handling: Added
onSubmit handler handleSubmit for form submission.
- Password Confirmation: Added a check to ensure that the password and repeat password match.
- API Request: Made a POST request to
/api/v1/user/register with the necessary registration data.
- Routing: Used
useRouter to redirect the user to the login page upon successful registration.
- Error Handling: Implemented error handling for unsuccessful registration attempts and displayed appropriate messages.
- Input Updates: Removed
name and last_name inputs since they are not required by the backend API.
Additional Notes:
- JWT Token Storage: Storing the JWT token in
localStorage is common, but be cautious as it may lead to security vulnerabilities like XSS attacks. Consider using HTTP-only cookies if security is a major concern.
- Protected Routes: For any other protected routes or components, ensure you check for authentication and redirect accordingly.
- API Base URL: If your backend API is hosted on a different domain or port, make sure to configure a proxy or adjust the fetch URLs accordingly.
- CORS Issues: If you encounter CORS errors, ensure that your backend is configured to accept requests from your frontend's domain.
These modifications should make your Next.js project properly interact with the backend API you've provided. If you have any components like UserAddReport or GoogleMapParent, make sure they also handle API requests and token authentication as needed.