Skip to content

Commit b92c085

Browse files
author
Vianpyro
committed
Refactor login component to use Composition API and improve error handling
1 parent 05d4681 commit b92c085

File tree

1 file changed

+38
-38
lines changed

1 file changed

+38
-38
lines changed
Lines changed: 38 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,57 @@
11
<template>
2-
<form id="login-form" @submit.prevent="login()">
2+
<form id="login-form" @submit.prevent="login">
33
<input type="email" id="login-email" name="email" v-model="email" placeholder="Email" required>
44
<input type="password" id="login-password" name="password" v-model="password" placeholder="Password" required>
55
<button type="submit">Login</button>
66
</form>
77
</template>
88

99
<script setup>
10+
import { ref } from 'vue';
1011
import { useRouter } from 'vue-router';
12+
import { useCookie } from '#app';
1113
1214
const router = useRouter();
13-
</script>
1415
15-
<script>
16-
export default {
17-
data() {
18-
return {
19-
email: '',
20-
password: ''
21-
};
22-
},
23-
methods: {
24-
login() {
25-
fetch('http://localhost:5000/auth/login', {
26-
method: 'POST',
27-
headers: { 'Content-Type': 'application/json' },
28-
body: JSON.stringify({
29-
email: this.email,
30-
password: this.password,
31-
}),
32-
})
16+
const email = ref('');
17+
const password = ref('');
18+
19+
const login = async () => {
20+
try {
21+
const data = await fetch('http://localhost:5000/auth/login', {
22+
method: 'POST',
23+
headers: { 'Content-Type': 'application/json' },
24+
body: JSON.stringify({
25+
email: email.value, // Correct usage of ref
26+
password: password.value, // Correct usage of ref
27+
}),
28+
})
3329
.then(response => {
34-
if (response.ok) {
35-
return response.json();
36-
} else {
30+
if (!response.ok) {
3731
throw new Error('Login failed');
3832
}
33+
return response.json(); // Parse JSON only if response is OK
3934
})
40-
.then(data => {
41-
console.log('Login successful:', data);
35+
.then(data => data.data);
4236
43-
// Create or update session cookies
44-
const accessToken = useCookie('access_token');
45-
const refreshToken = useCookie('refresh_token');
46-
accessToken.value = data.access_token;
47-
refreshToken.value = data.refresh_token;
37+
// Use cookies to store tokens
38+
const accessToken = useCookie('access_token', {
39+
maxAge: 60 * 60 * 1, // 1 hour
40+
path: '/',
41+
});
4842
49-
router.push('/');
50-
})
51-
.catch(error => {
52-
console.error('Error:', error);
53-
});
54-
}
55-
},
56-
}
43+
const refreshToken = useCookie('refresh_token', {
44+
maxAge: 60 * 60 * 24 * 30, // 30 days
45+
path: '/',
46+
});
47+
48+
accessToken.value = data.access_token;
49+
refreshToken.value = data.refresh_token;
50+
51+
// Navigate to home page
52+
router.push('/');
53+
} catch (error) {
54+
console.error('Error:', error);
55+
}
56+
};
5757
</script>

0 commit comments

Comments
 (0)