Skip to content
Snippets Groups Projects
Commit 02e116b5 authored by satwikShresth's avatar satwikShresth
Browse files

adding frontend guide

parent ef96169f
No related branches found
No related tags found
No related merge requests found
...@@ -42,7 +42,7 @@ After running `docker compose up`, you need to configure the S3 access: ...@@ -42,7 +42,7 @@ After running `docker compose up`, you need to configure the S3 access:
- Username: minioadmin - Username: minioadmin
- Password: minioadmin - Password: minioadmin
3. Generate an access key and secret key in the MinIO UI 3. Generate an access key and secret key in the MinIO UI
4. Update your `.env` file with these keys: 4. Update your [`.env`](./.env) file with these keys:
``` ```
S3_ACCESS_KEY={accesskey} S3_ACCESS_KEY={accesskey}
S3_SECRET_KEY={secretkey} S3_SECRET_KEY={secretkey}
...@@ -70,7 +70,7 @@ Once the Inspiration project is running, you can access these endpoints: ...@@ -70,7 +70,7 @@ Once the Inspiration project is running, you can access these endpoints:
## Environment Variables ## Environment Variables
The Inspiration project requires several environment variables to be set in the `.env` file: The Inspiration project requires several environment variables to be set in the [`.env`](./.env) file:
### Database Configuration ### Database Configuration
- `POSTGRES_PASSWORD` - Password for PostgreSQL - `POSTGRES_PASSWORD` - Password for PostgreSQL
...@@ -122,7 +122,7 @@ To monitor Redis after successfully setting up the project: ...@@ -122,7 +122,7 @@ To monitor Redis after successfully setting up the project:
2. Add a new Redis database connection with the following details: 2. Add a new Redis database connection with the following details:
- Host: redis - Host: redis
- Port: 6379 - Port: 6379
- Connection string: redis://redis:6379 (same as the REDIS_ENDPOINT value in your .env file) - Connection string: redis://redis:6379 (same as the REDIS_ENDPOINT value in your [`.env`](./.env) file)
## Common Problems and Solutions ## Common Problems and Solutions
...@@ -131,7 +131,7 @@ To monitor Redis after successfully setting up the project: ...@@ -131,7 +131,7 @@ To monitor Redis after successfully setting up the project:
**Problem**: Backend can't connect to the database **Problem**: Backend can't connect to the database
**Solution**: **Solution**:
1. Check that PostgreSQL is running: `docker compose ps` 1. Check that PostgreSQL is running: `docker compose ps`
2. Verify database environment variables in `.env` file 2. Verify database environment variables in [`.env`](./.env) file
3. Ensure database has been initialized: `docker compose logs database` 3. Ensure database has been initialized: `docker compose logs database`
4. Try restarting the database service: `docker compose restart database` 4. Try restarting the database service: `docker compose restart database`
...@@ -139,7 +139,7 @@ To monitor Redis after successfully setting up the project: ...@@ -139,7 +139,7 @@ To monitor Redis after successfully setting up the project:
**Problem**: Services fail to start with errors about missing environment variables **Problem**: Services fail to start with errors about missing environment variables
**Solution**: **Solution**:
1. Create a `.env` file in the project root if it doesn't exist 1. Create a [`.env`](./.env) file in the project root if it doesn't exist
2. Ensure all required variables are set (see Environment Variables section) 2. Ensure all required variables are set (see Environment Variables section)
3. Run `docker compose down` and then `docker compose up --build` to rebuild with the new variables 3. Run `docker compose down` and then `docker compose up --build` to rebuild with the new variables
...@@ -157,7 +157,7 @@ To monitor Redis after successfully setting up the project: ...@@ -157,7 +157,7 @@ To monitor Redis after successfully setting up the project:
**Problem**: File uploads fail or S3 storage isn't accessible **Problem**: File uploads fail or S3 storage isn't accessible
**Solution**: **Solution**:
1. Check that MinIO is running: `docker compose ps minio` 1. Check that MinIO is running: `docker compose ps minio`
2. Verify S3 environment variables in `.env` file 2. Verify S3 environment variables in [`.env`](./.env) file
3. Ensure MinIO is healthy: `curl -f http://localhost:9000/minio/health/live` 3. Ensure MinIO is healthy: `curl -f http://localhost:9000/minio/health/live`
4. Default credentials are: minioadmin/minioadmin 4. Default credentials are: minioadmin/minioadmin
5. Check MinIO UI at http://localhost:9001 to verify bucket configuration 5. Check MinIO UI at http://localhost:9001 to verify bucket configuration
... ...
......
# Understanding TanStack Router in Your React Application
## Overview of Your Application Structure
Your application uses TanStack Router for routing, React Query for data fetching, and follows a structure with protected and public routes. Let me explain the key components:
## The Route Structure
Looking at the generated `routeTree.gen.ts` file, your application has the following route structure:
- Root routes:
- `/login` - Login page
- `/signup` - Signup page
- `/recover-password` - Password recovery
- `/reset-password/$token` - Password reset with token
- `/_protected` - Protected area that requires authentication
- Protected routes (nested under `/_protected`):
- `/` - Protected index/dashboard
- `/admin` - Admin section
- `/settings` - User settings
- `/work-order` - Work order management
- `/dashboard/$` - Dynamic dashboard with parameters
## Main Application Setup (main.tsx)
Your `main.tsx` file sets up:
1. **React Query Client**: For API data fetching with automatic error handling
2. **TanStack Router**: For routing based on the generated route tree
3. **Authentication Management**: Automatic redirection to login for unauthorized requests
## Development and Build Commands
Your package.json includes several useful commands:
- `npm run dev`: Starts the development server using Vite
- `npm run build`: Compiles TypeScript and builds the production version
- `npm run lint`: Runs code linting with Biome
- `npm run preview`: Previews the production build locally
- `npm run gen:client` and `npm run gen:client:auth`: Generate API client code from OpenAPI specs
## Vite Configuration
Your Vite configuration:
- Uses React plugin
- Integrates TanStack Router plugin
- Sets up API proxying for development
- Includes path aliasing for cleaner imports
## The API Integration Workflow
A key feature of your setup is the API client generation. When you run `npm run gen:client`, it creates TypeScript client code from your OpenAPI specifications. This ensures:
1. Type-safe API calls
2. Consistent API access patterns
3. Automatic validation
All API endpoints should be accessed through React Query hooks using the generated clients, not with direct fetch/axios calls. This provides:
- Automatic caching
- Loading and error states
- Refetching on window focus
- Consistent error handling
## Authentication Flow
Your application handles authentication by:
1. Redirecting unauthorized users to `/login`
2. Protecting routes under the `/_protected` path
3. Automatically handling 401/403 errors by redirecting to login
## For New Developers
If you're new to this project:
1. Start with `npm install` to get all dependencies
2. Run `npm run gen:client` to generate the API clients
3. Use `npm run dev` to start development
4. Navigate the route structure to understand the application flow
5. Look at the generated clients in the `/client` directory to see available API endpoints
6. Always use React Query hooks with the generated clients for data fetching
The TanStack Router generates type-safe routes, meaning you'll get autocomplete and type checking when navigating between routes in your code.
### The Problem with useEffect for Data Fetching
In traditional React applications, data fetching often happens inside `useEffect` hooks when components mount:
```jsx
useEffect(() => {
// Fetch data when component mounts
fetchData().then(setData);
}, []);
```
This approach has several drawbacks:
- Data loading starts only after component rendering
- Creates waterfall requests
- Manages loading/error states in component state
- Difficult to coordinate data dependencies
### TanStack Router's Superior Approach: Route Loaders
Your application uses TanStack Router's loader pattern, which is a much better solution:
```typescript
export const Route = createFileRoute('/_protected/dashboard/$')({
beforeLoad: ({ params }) => params?._splat?.trim(),
loader: async ({ params: { _splat: prefix }, context: { queryClient } }) =>
queryClient.prefetchQuery(getFilecontentTreeOptions({
query: { prefix }
})),
}
```
#### Benefits of Route Loaders:
1. **Data Prefetching**: Data loading starts before component rendering, eliminating loading spinners in many cases
2. **Parallel Data Loading**: Multiple loaders run in parallel, preventing request waterfalls
3. **Automatic Integration with React Query**: Uses the same caching system
4. **Type Safety**: Full TypeScript support across params, query options, and returned data
5. **Access to Route Context**: Can use route parameters directly
6. **Improved Performance**: Better user experience with reduced loading times
#### How It Works:
1. **Route Definition**: Each route file exports a `Route` object with optional `loader` function
2. **Parameter Processing**: The `beforeLoad` function can transform route parameters
3. **Data Loading**: The `loader` function prefetches data using React Query before rendering
4. **Component Access**: Components can access this data with the `useLoaderData` hook
### The Workflow for API Integration
1. Run `npm run gen:client` to generate type-safe API clients
2. Define route loaders that use React Query's `prefetchQuery` with the generated client options
3. Access the data in your components with `useLoaderData()` or `useQuery()`
Example of using loaded data in a component:
```tsx
function DashboardView() {
// Access data from the loader
const prefetchedData = useLoaderData();
// Or use the same query configuration to access cached data
const { data } = useQuery(getFilecontentTreeOptions({
query: { prefix }
}));
// Render with the data...
}
```
This pattern eliminates most cases where you'd traditionally use `useEffect` for data fetching on component mount, leading to cleaner code and better performance.
By following this pattern, you'll create a more responsive application with proper loading states and better user experience.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment