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.
Step 1: Add state in App.tsx
Inside our App component, add:
const [showAddTaskForm, setShowAddTaskForm] = useState(false);
<AppHeader
isAuthenticated={!!accessToken}
onAddTaskClick={() => setShowAddTaskForm(true)}
/>
{accessToken && showAddTaskForm && (
<main className="add-task-form">
<h2>Add a new task</h2>
</main>
)}
Step 2: Update AppHeader.tsx
Add the callback to our existing interface:
interface AppHeaderProps {
isAuthenticated: boolean,
onAddTask: (addTask: boolean) => void
}
<Button appearance="primary" onClick={() => props.onAddTask(true)}>
Add Task
</Button>
Create AddTaskForm.tsx
Let’s create a separate component rather than putting the form directly inside App.tsx. Create: frontend/src/features/tasks/components/AddTaskForm.tsx
For our first iteration, we’ll add just two fields: Title and Description. Use your existing Fluent UI components:
import { useState } from "react";
import { Button, Field, Input, Textarea } from "@fluentui/react-components";
interface AddTaskFormProps {
onCancel: () => void;
}
function AddTaskForm(props: AddTaskFormProps) {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const handleAddtask = () => {
}
return (
<form onSubmit={handleAddtask}>
<h2>Add a new task</h2>
<Input
name="title"
value={title}
placeholder="Enter task title"
onChange={(e) => setTitle(e.target.value)} />
<Textarea
name="description"
value={description}
placeholder="Enter task description"
rows={4}
onChange={(e) => setDescription(e.target.value)} />
<Button type="button" onClick={onCancel}>
Cancel
</Button>
</form>
);
}
export default AddTaskForm;
Connect AddTaskForm to App.tsx
Currently, App.tsx still renders the placeholder heading instead of your new component.
import AddTaskForm from "./features/tasks/components/AddTaskForm";
{loggedIn && openAddForm && (
<main className="add-task-form">
<AddTaskForm />
</main>
)}
Step 2: Add a Cancel button
Let’s allow the user to close the form. In AddTaskForm.tsx, add a prop:
AddTaskForm:
interface AddTaskFormProps {
onCancel: () => void;
}
function AddTaskForm({ onCancel }: AddTaskFormProps) {
form:
<Button type="button" onClick={onCancel}>
Cancel
</Button>
App:
<AddTaskForm onCancel={() => setOpenAddForm(false)} />
Convert the Add Form into a Pop up Box
App.tsx should manage the dialog’s visibility state, while AddTaskForm.tsx should own the dialog UI and form fields. The parent doesn’t need to know how Fluent UI Dialog works.
1. Update AddTaskForm.tsx
Add the Dialog components to your existing imports:
import { useState } from "react";
import {
Dialog,
DialogSurface,
DialogBody,
DialogTitle,
DialogContent,
Button,
Textarea,
Input,
Field
} from "@fluentui/react-components";
interface AddTaskFormProps {
open: boolean,
onClose: () => void
}
function AddTaskForm(props: AddTaskFormProps) {
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const handleAddTask = () => {
}
return (
<Dialog open={props.open} onOpenChange={(_, data) => { if (!data.open) props.onClose() }}>
<DialogSurface>
<DialogBody>
<DialogTitle></DialogTitle>
<DialogContent>
<form className="add-task-form" onSubmit={handleAddTask}>
<h2>Add a New Task</h2>
<Field label="Task title" required>
<Input
className="add-task-form__input"
name="title"
value={title}
placeholder="Enter task title"
onChange={(e) => setTitle(e.target.value)} />
</Field>
<Field label="Description">
<Textarea
className="add-task-form__input"
name="description"
value={description}
placeholder="Enter task description"
rows={4}
onChange={(e) => setDescription(e.target.value)} />
</Field>
<div className="add-task-form__actions">
<Button type="button" onClick={props.onClose}>
Cancel
</Button>
<Button type="submit" appearance="primary">
Add
</Button>
</div>
</form>
</DialogContent>
</DialogBody>
</DialogSurface>
</Dialog>
);
}
export default AddTaskForm;
2. Add CSS – Add this to your existing CSS file:
.add-task-form {
display: flex;
flex-direction: column;
gap: 20px;
min-width: 350px;
padding-top: 12px;
}
.add-task-form__input {
width: 100%;
}
.add-task-form__actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 8px;
}
App.tsx:
{loggedIn && (
<AddTaskForm
open={openAddForm}
onClose={() => setOpenAddForm(false)}
/>
)}
Why this design?
App.tsx: Controls when the dialog opens and closes.AddTaskForm.tsx: Owns the Dialog, form fields and form behaviour.AppHeader.tsx: Only triggers the Add Task action.
This keeps each component focused on its responsibility without adding unnecessary abstractions.
Implement Add Task functionality
We’ll connect our existing createTask() service to AddTaskForm.
The flow will be:
- Validate the title.
- Call
createTask()with the form values and access token. - Add the returned task to the existing
tasksstate inApp.tsx. - Close the dialog after successful creation.
We’ll also display Rails validation errors in the form instead of using browser alerts. Let’s connect the form to our existing createTask() API service.
We’ll keep the responsibilities simple:
AddTaskForm: Handles input values, submission, loading and errors.App.tsx: Owns the task list and updates it when a task is created.taskService.ts: Makes the API request.
Step 1: Pass the required props to AddTaskForm, Import the API service, Add loading and error states
The form needs the access token to call Rails and a callback to notify App.tsx when creation succeeds.
Inside AddTaskForm, alongside your existing title and description states, add: loading, error
1. Update AddTaskForm.tsx
import type { Task } from "../types/task";
import { createTask } from "../services/taskService";
...
interface AddTaskFormProps {
open: boolean;
accessToken: string;
onClose: () => void;
onTaskCreated: (task: Task) => void;
}
...
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
...
function AddTaskForm({
open,
accessToken,
onClose,
onTaskCreated
}: AddTaskFormProps) {
2. Update App.tsx
Pass the token and callback:
{accessToken && (
<AddTaskForm
open={openAddForm}
accessToken={accessToken}
onClose={() => setOpenAddForm(false)}
onTaskCreated={(task) => {
setTasks((currentTasks) => [task, ...currentTasks]);
}}
/>
)}
Why [task, ...currentTasks]?
It creates a new array with the newly created task at the beginning, followed by the existing tasks. This is important because React state should be updated immutably.
Step 3: Implement handleAddTask
Replace our empty function with:
const handleAddTask = async () => {
setLoading(true);
setError(null);
try {
const task = await createTask(
{
task: {
title: title.trim(),
description: description.trim() || null,
status: "pending"
}
},
accessToken
);
onTaskCreated(task);
setTitle("");
setDescription("");
onClose();
} catch (error) {
setError(
error instanceof Error ? error.message : "Failed to create task"
);
} finally {
setLoading(false);
}
};
Check our Add Task Functionality:


