In the last session we have completed the Login form implementation with conditional UI. We also covered Github Actions for Frontend CI. Now Let’s move on to loading tasks, creating and deleting task actions.
Load tasks from the Rails API
We’ll now connect the React UI to the authenticated Tasks API.
Let’s do this in small steps:
- Fetch the logged-in user’s tasks using the access token.
- Display the returned tasks in
TaskList. - Load the selected task’s details.
- Later, implement create, edit and delete.
Step 1: Check our existing Task type
export type Task = {
id: number,
title: string,
description: string,
status: TaskStatus,
created_at: string,
updated_at: string
}
Step 2: Verify the API response
# api/v1/tasks_controller.rb
def index
tasks = current_user.tasks.order(created_at: :desc)
render json: TaskBlueprint.render_as_hash(
tasks,
root: :data
), status: :ok
end
# backend/app/blueprints/task_blueprint.rb
class TaskBlueprint < Blueprinter::Base
identifier :id
fields :title, :description, :status, :created_at, :updated_at
end
Now we know the exact response structure. Because you use root: :data, the Tasks API returns a response like this:
{
"data": [
{
"id": 1,
"title": "Learn React",
"description": "Practice React hooks",
"status": "pending",
"created_at": "...",
"updated_at": "..."
}
]
}
The current_user.tasks scope also ensures that the endpoint returns only the logged-in user’s tasks.
Step 3: Create taskService.ts
Let’s create a service responsible for fetching tasks. Create: frontend/src/features/tasks/services/taskService.ts
For this first step, add a function that makes the authenticated GET request:
import type { Task } from "../types/task";
interface TaskResponse {
data: Task[]
}
export async function fetchTasks(accessToken: string): Promise<Task[]> {
const response = await fetch(import.meta.env['VITE_API_BASE_URL'] + "/api/v1/tasks", {
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken
},
credentials: 'include'
});
if(!response.ok) {
throw new Error("Failed to load tasks");
}
const result: TaskResponse = await response.json();
return result.data;
}
One small cleanup: for this GET request, we don’t need the Content-Type header or credentials: 'include'. The endpoint uses JWT authentication through the Authorization header. Keep credentials: 'include' in the login and refresh requests where cookies are required.
1. Authorization header Authorization: Bearer ${accessToken}. This sends the JWT to Rails. Your BaseController can then verify it and identify the current user.
2. Response type
type TasksResponse = {
data: Task[];
};
This represents the JSON structure returned by your TaskBlueprint.
3. Return only the tasks return result.data;
The component needs the task array, not the entire API response.
Fetch tasks in App.tsx
We’ll use React’s useEffect to fetch tasks automatically after a successful login.
1. Update your React import: import { useEffect, useState } from "react";
2. Import the service: import { fetchTasks } from "./features/tasks/services/taskService";
3. Add this effect inside App, alongside your existing state declarations:
useEffect(() => {
async function loadTasks() {
if (!accessToken) return;
try {
const tasks = await fetchTasks(accessToken);
setTasks(tasks);
} catch (error) {
console.log("Failed to load tasks: ", error);
}
}
loadTasks();
}, [accessToken]);
Understand what happens
- Initially,
accessTokenisnull, so the effect does nothing. - After login,
setAccessTokenupdates the token. - React runs the effect again because
accessTokenchanged. fetchTasks()requests tasks from Rails.setTasks(tasks)updates the React state, andTaskListreceives the new tasks through props.
Add this effect to App.tsx and test it.
Let’s implement Add Task incrementally, using your existing Fluent UI components and Rails API.
We’ll follow this flow:
- Clicking Add Task opens a form.
- The form accepts a title, description and status.
- React sends a
POSTrequest to Rails. - On success, the new task appears in the task list.
We’ll start by verifying the backend API before writing the frontend code.
Step 1: Check the Rails create action
def create
task = current_user.tasks.new(task_params)
if task.save
render json: TaskBlueprint.render_as_hash(
task,
root: :data
), status: :created
else
render_validation_errors(task)
end
end
Our create action confirms a few things:
- Rails creates tasks through
current_user.tasks, so the task is associated with the authenticated user. - On success, it returns HTTP
201 Created. - The response is wrapped inside a top-level
dataproperty. - Validation failures are handled by
render_validation_errors(task).
Now we know exactly what the frontend needs to send. Our Rails controller expects this JSON structure because of params.require(:task):
{
"task": {
"title": "Learn React",
"description": "Practice React forms",
"status": "pending"
}
}
Validation failures return:
{
"errors": ["Title can't be blank"]
}
Add createTask() to taskService.ts
We’ll reuse the same service file that already contains fetchTasks().
Add this function below fetchTasks():
export async function createTask(params: CreateTaskParams, accessToken:string): Promise<Task> {
const response = await fetch(import.meta.env['VITE_API_BASE_URL'] + "/api/v1/tasks", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken
},
body: JSON.stringify(params)
});
const result = await response.json();
if(!response.ok) {
throw new Error(result.errors?.join(", ") ?? "Failed to create task");
}
return result.data;
}
Why return Task?
Our Rails controller returns the newly created task under data. We return that task so React can add it to the existing task list without making another GET request.
Two small cleanup points
credentials: 'include'isn’t needed here because the Tasks API authenticates using the Bearer token, not a cookie.- Use
result.errors?.join(", ")so the error handler doesn’t itself fail when the response has noerrorsproperty.
