Skip to content

The Rails Drop

find here about Ruby, Ruby On Rails, Linux etc…

The Rails Drop

Tag: Login

Task Manager application: Complete Login form with task component communication

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:

  • true for successful HTTP responses (status 200-299).
  • false for 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:

  1. Login succeeds: returns the response data.
  2. Login fails with an HTTP error: throws an error with the backend’s message.
  3. 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.
  • catch handles both HTTP errors thrown by our service and network errors.
  • finally executes 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:

  1. Open your browser’s Developer Tools → Network.
  2. Submit the login form.
  3. Select the /api/v1/auth/login request.
  4. 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

Unknown's avatarAuthor AbhilashPosted on December 1, 2026December 1, 2026Categories Rails 8.0, React, Ruby 4.0, Ruby On RailsTags Login, React, Ruby, Ruby On RailsLeave a comment on Task Manager application: Complete Login form with task component communication
December 2026
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
28293031  
« Nov    

Recent Posts

  • Task Manager application: Complete Login form with task component communication
  • Task Manager application: Integrate React useState and component communication
  • Create Task Manager app: Setup React application and Integrate Fluent UI
  • Create Task Manager app: Create Task CRUD supported by JWT authentication, Integrate Github Actions with Rspec tests
  • Create Task Manager app: Implement – Registration and Login APIs, Setup JSON Serializer
  • Create Task Manager app: Implement – Rails API, JWT Authentication
  • Create Task Manager app: Setup backend – Rails models, tables, enums and add Rspec Tests
  • Implement Task Manager application with Ruby on Rails backend, React frontend, Postgresql, Rspec, Docker and Github Actions
  • Ractors and Ruby Box in Ruby 4: What Do They Mean for Rails?
  • Rails Encrypted Credentials: The Git Diff Feature You May Have Been Using Without Knowing
  • Web Application Testing: Rails, RSpec, Puppeteer and Playwright
  • Ruby Beyond CRuby: Why JRuby and TruffleRuby Exist? What Ruby 4.0 Really Changed
  • What Really Happens When Ruby Code Executes?
  • Build Rails 8 API + React + Vite from Scratch – Part 2
  • 📝 Software Documentation Best Practices: How Enterprise Teams Track Code Changes
  • OpenRouter AI: One API for Multiple AI Models
  • Integrate AI with Rails: Day 11 – RAG : Build Semantic Search
  • Integrate AI with Rails: Day 10 – RAG Part 2: embeddings
  • Integrate AI with Rails: Day 10 – RAG with PostgreSQL + pgvector – part 1
  • Integrate AI with Rails: Day 9 – implement OpenRouter model fallbacks
  • Integrate AI with Rails: Day 8 – Production Hardening of the AI Integration, add AI Observablility
  • Integrate AI with Rails: AI bootcamp for Developers – Day 7 – AI Response Streaming
  • Integrate AI with Rails: AI bootcamp for Developers – Day 6 – Build the Rails Chat UI | Prompt Builder | Chat Memory
  • Integrate AI with Rails: AI bootcamp for Developers – Day 5 –Use OpenRouter API, Create AI Chat service
  • Integrate AI with Rails: AI bootcamp for Developers – Day 4 -Practical Course – Part 3
  • Integrate AI with Rails: AI bootcamp for Developers – Day 4 -Practical Course – Part 2
  • Integrate AI with Rails: AI bootcamp for Developers – Day 4 -Practical Course – Part 1
  • Learn AI with Rails: AI Bootcamp for Developers – Building AI Applications in Ruby on Rails – Day 4
  • Learn AI with Rails: AI Bootcamp for Developers – RAG, Embeddings & Vector Databases – Day 3
  • Learn AI with Rails: AI Bootcamp for Developers – Prompt Engineering, AI APIs & Tool Calling – Day 2
  • Learn AI with Rails: AI Topics You Must Know as a Senior Developer – Day 1
  • Understading Rails 8.1 Action Controller Live SSE
  • Ruby’s Mysterious Symbols: The Syntax Every Ruby Developer Should Truly Understand
  • Rails Database Transactions: Developer’s Guide to Atomicity, Rollbacks, Savepoints and Transaction-Safe Design
  • CI/CD Pipeline for a Rails + React Application Using GitHub Actions

Archives

  • December 2026
  • November 2026
  • August 2026
  • July 2026
  • June 2026
  • May 2026
  • April 2026
  • March 2026
  • February 2026
  • January 2026
  • December 2025
  • November 2025
  • October 2025
  • September 2025
  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • August 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • October 2023
  • July 2023
  • June 2023
  • June 2022
  • May 2022
  • March 2022
  • December 2021
  • November 2021
  • July 2021
  • March 2021
  • October 2020
  • April 2020
  • March 2020
  • September 2019
  • July 2019
  • June 2019
  • May 2018
  • April 2018
  • September 2017
  • August 2017
  • June 2017
  • April 2017
  • June 2016
  • May 2016
  • March 2016
  • February 2016
  • September 2015
  • August 2015
  • April 2015
  • March 2015
  • September 2014
  • October 2013
  • September 2013
  • July 2013
  • April 2013
  • January 2013
  • December 2012
  • November 2012
  • August 2012
  • July 2012
  • April 2012
  • February 2012
  • January 2012
  • November 2011
  • October 2011
  • August 2011
  • June 2011
  • March 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
The Rails Drop Start a Store on WordPress.com.
  • Subscribe Subscribed
    The Rails Drop
    Join 41 other subscribers

    Have a WordPress.com account? Log in now.

  • The Rails Drop
    View site in Reader
    Manage subscriptionsSign upLog in
    Report this content
    Collapse this bar
Loading Comments...