In our last session we have implemented a basic structure of login form where we call the auth service, to make an API call to our backend Rails API.
Now we modify and improve each of our files one by one.
We removed the try, catch blocks. Our current auth service file look like this:
import type { LoginRequest } from "../types/auth";
export async function loginRequest(args: LoginRequest) {
const response = await fetch(import.meta.env['VITE_API_BASE_URL'] + "/api/v1/auth/login", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
// Essential for receiving and sending session cookies cross-origin
credentials: 'include',
body: JSON.stringify(args)
});
const data = await response.json();
return data;
}
Now let’s handle the next issue in authService.ts: HTTP error responses.
Currently, even when the backend returns 401 Unauthorized, your function parses the response and returns it as if the request succeeded.
Step 2: Check response.ok
The Fetch API provides response.ok:
truefor successful HTTP responses (status 200-299).falsefor responses such as 401, 403, and 422.
After parsing the response JSON, add this check:
if (!response.ok) {
throw new Error(data.errors?.[0] ?? "Login failed");
}
Our function will now behave like this:
- Login succeeds: returns the response data.
- Login fails with an HTTP error: throws an error with the backend’s message.
- Network failure: the Fetch API error propagates to the caller.
Why are we throwing the error?
Because the component calling loginRequest() should decide how to display the error to the user. The service should handle the API request, not React UI state.
A network error does not become "Login failed" automatically. There are two different paths:
1. Backend returns HTTP 401
fetch() receives the response successfully. Then response.ok is false, so your code executes: throw new Error(data.errors?.[0] ?? "Login failed");
2. Network failure
For example, the Rails server is stopped. fetch() itself rejects its Promise. Execution jumps directly to the caller’s catch block. Your response.ok check is never reached.
So the component calling loginRequest() needs to catch both errors.
Let’s update the handleLogin function from LoginForm
Update LoginForm with:
const handleLogin = async (event: React.SubmitEvent<HTMLFormElement>) => {
event.preventDefault();
setLoading(true);
setError([]);
....
....
try {
await loginRequest(params);
alert('Logged in successfully');
// props.setTasks(data);
} catch (error) {
setError([error instanceof Error ? error.message : "Something went wrong"])
} finally {
setLoading(false);
}
}
With newer React TypeScript definitions (@types/react 19.2.10+), FormEvent is deprecated in favour of SubmitEvent. Our React.SubmitEvent<HTMLFormElement> is the appropriate type.
Understand these three things
await loginRequest(params)waits for the API response.catchhandles both HTTP errors thrown by our service and network errors.finallyexecutes whether the request succeeds or fails. That’s where we reset the loading state.
Verify the login response
Before connecting the access token to App.tsx, let’s verify the actual response structure.
do this:
- Open your browser’s Developer Tools → Network.
- Submit the login form.
- Select the
/api/v1/auth/loginrequest. - Open its Response tab.
Check whether the response has a top-level data property or whether access_token is directly at the top level.
I get Reponse as:
{
"data": {
"access_token": "eyJhbGciOiJIUzI1NiJ9.ey......",
"expires_in": 600,
"token_type": "Bearer",
"user": {
"id": 1,
"email": "test@example.com"
}
}
}
The response matches your existing LoginResponse type. The access token is inside response.data.access_token
In authService.ts, update the import:
import type { LoginRequest, LoginResponse } from "../types/auth";
Then update the function signature:
export async function loginRequest(
args: LoginRequest
): Promise<LoginResponse> {
Finally, change the return statement:
return data as LoginResponse;
The as LoginResponse tells TypeScript to treat the parsed JSON as this response structure. It does not validate the JSON at runtime.
Why are we doing this?
When you call: const response = await loginRequest(params);
TypeScript will now understand that:
response.data.access_token
response.data.user
response.data.expires_in
are available.
Next, we’ll pass the access token from LoginForm to App.tsx and store it in React state.
Send the access token from LoginForm to App.tsx
Currently, LoginForm receives the login response but doesn’t pass the access token anywhere. We’ll use a callback prop to communicate with the parent component.
1. Update LoginForm.tsx
Add a prop interface:
interface LoginFormProps {
onLoginSuccess: (accessToken: string) => void;
}
Update your component declaration to receive this prop:
function LoginForm({ onLoginSuccess }: LoginFormProps) {
Inside your existing try block, update the successful login handling:
const response = await loginRequest(params);
onLoginSuccess(response.data.access_token);
Remove the old success alert for now.
What is happening here?
LoginFormcalls the login API.- The API returns the access token.
onLoginSuccess()sends that token to its parent component,App.tsx.
This is a common React pattern: child-to-parent communication using callback props.
Now we’ll store the access token in React state inside App.tsx.
Step 1: Add access token state
Inside your App component, next to your existing tasks state, add:
const [accessToken, setAccessToken] = useState<string | null>(null);
Purpose: This stores the JWT in memory. Other parts of App can access it when making authenticated API requests. We are not using localStorage.
Step 2: Pass the state setter to LoginForm
Find your existing login form: <LoginForm />
Change it to: <LoginForm onLoginSuccess={setAccessToken} />
When login succeeds, LoginForm calls onLoginSuccess(accessToken), which updates the state in App.
Step 3: Use the token state
To avoid keeping the login form visible after successful login, update its rendering:
{!accessToken && (
<main className="login-form">
<LoginForm onLoginSuccess={setAccessToken}></LoginForm>
</main>
)}
{accessToken && (
<main className="task-workspace">
<aside className="task-list-panel">
.....
Add Authenticated condition in AppHeader Component
We’ll keep the AppHeader visible on both screens, but show the Add Task button only after login.
Let’s use a boolean prop called isAuthenticated.
Step 1: Add a prop to AppHeader.tsx
Add this interface above the component:
interface AppHeaderProps {
isAuthenticated: boolean;
}
Update the component declaration: function AppHeader({ isAuthenticated }: AppHeaderProps) {
Step 2: Conditionally render the button
Wrap your existing Add Task button:
{isAuthenticated && (
<Button appearance="primary">
Add Task
</Button>
)}
Step 3: Pass the prop from App.tsx
Change: <AppHeader />
To: <AppHeader isAuthenticated={!!accessToken} />
!!accessToken converts the token into a boolean: true when logged in and false otherwise. The Add Task button will now appear only after successful login.
Note: The button is still only a visual placeholder. We’ll implement its click behaviour when we work on task creation.
Now our App without login looks like this: Clean state before Login user

