From 0ef310fecd699416598f2e5ad720a895092b5c35 Mon Sep 17 00:00:00 2001 From: Manuel Bustillo Date: Sun, 1 Dec 2024 17:47:42 +0100 Subject: [PATCH] Use Accept header to avoid unnecessary call to get current user --- app/api/authentication.tsx | 22 ++++++++++------------ app/ui/components/login-form.tsx | 6 +++--- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/app/api/authentication.tsx b/app/api/authentication.tsx index 3275700..3bc9272 100644 --- a/app/api/authentication.tsx +++ b/app/api/authentication.tsx @@ -3,17 +3,25 @@ import { getCsrfToken } from '@/app/lib/utils'; import { User } from '@/app/lib/definitions'; -export function login({ email, password, onLogin }: { email: string, password: string, onLogin: () => void }) { +export function login({ email, password, onLogin }: { email: string, password: string, onLogin: (user: User) => void }) { console.log(email, password); return fetch("/api/default/users/sign_in", { method: 'POST', body: JSON.stringify({ user: { email, password } }), headers: { + 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRF-TOKEN': getCsrfToken(), } }) - .then(onLogin) + .then((response) => response.json()) + .then((data: any) => { + console.log(data); + onLogin({ + id: data.id || '', + email: data.email || '', + }); + }) .catch((error) => console.error(error)); } @@ -26,13 +34,3 @@ export function logout({ onLogout }: { onLogout: () => void }) { }).then(onLogout) .catch((error) => console.error(error)); } - -export function getCurrentUser({ onLoad }: { onLoad: (user: User) => void }) { - fetch("/api/default/users/current") - .then((response) => response.json()) - .then((data) => { - onLoad(data); - }, (error) => { - return null; - }); -} \ No newline at end of file diff --git a/app/ui/components/login-form.tsx b/app/ui/components/login-form.tsx index 13c6349..3685c85 100644 --- a/app/ui/components/login-form.tsx +++ b/app/ui/components/login-form.tsx @@ -4,7 +4,7 @@ import { FloatLabel } from 'primereact/floatlabel'; import { InputText } from 'primereact/inputtext'; -import { getCurrentUser, login } from '../../api/authentication'; +import { login } from '../../api/authentication'; import { useState, useEffect } from 'react'; import { classNames } from './button'; import { useRouter } from 'next/navigation' @@ -38,8 +38,8 @@ export default function LoginForm() { onClick={() => login({ email: email, password: password, - onLogin: () => { - getCurrentUser({ onLoad: (user) => setCurrentUser(user) }); + onLogin: (user) => { + setCurrentUser(user); router.push('/dashboard') } })}>