index.js
Overview
The index.js file defines a React functional component responsible for rendering the main user interface of a web page that handles user authentication status. It leverages the SWR (stale-while-revalidate) React hook for data fetching and caching, to retrieve the current user's session data from the /api/user endpoint.
Depending on whether the user is logged in or not, the component renders different UI elements:
If the user data is still loading, it displays a loading message.
If the user is authenticated, it shows a welcome message with the user's name and avatar, along with a Logout button.
If the user is not authenticated, it prompts the user to login with a Login button.
The component uses external utility functions (login, logout) to handle authentication actions and a reusable Button component for UI consistency.
Detailed Explanation
Imports
Button
Custom button component imported from../components/button. Used for rendering clickable buttons in the UI.fetch
A custom fetch utility from../libs/fetchto perform HTTP requests compatible with SWR’s data fetching paradigm.{ login, logout }
Authentication utility functions imported from../libs/auth:login()initiates the login process.logout()initiates the logout process.
useSWR
React hook from the swr library that handles data fetching, caching, and revalidation.
Index Component
export default function Index() {
const { data, mutate } = useSWR('/api/user', fetch)
if (!data) return <h1>loading...</h1>
if (data.loggedIn) {
return (
<div>
<h1>Welcome, {data.name}</h1>
<img src={data.avatar} width={80} />
<Button onClick={() => {
logout()
mutate() // after logging in/out, we mutate the SWR
}}>Logout</Button>
</div>
)
} else {
return (
<div>
<h1>Please login</h1>
<Button onClick={() => {
login()
mutate()
}}>Login</Button>
</div>
)
}
}
Purpose
Fetches the current user state from
/api/user.Conditionally renders UI based on authentication status.
Provides login and logout actions that trigger SWR revalidation to update UI immediately after state changes.
Parameters
This is a React functional component with no input parameters.
Return Value
Returns JSX elements representing the UI:
Loading message while fetching user data.
Welcome view if logged in.
Login prompt if not logged in.
Usage Example
This component is typically used as the default export for the main landing page or home route in a React app:
import Index from './index'
function App() {
return <Index />
}
Important Implementation Details
SWR Fetching and Mutation
The component usesuseSWRto fetch the user data with a key/api/user. Thefetchutility handles the actual HTTP request.When the login or logout button is clicked, the respective function (
loginorlogout) is called.Immediately after,
mutate()is called to trigger SWR to re-fetch/api/userdata, ensuring the UI reflects the updated authentication state without a full page reload.
Data Shape Assumption
The component expects the user data object from/api/userto have at least the following structure:{ loggedIn: boolean, name: string, avatar: string // URL to user's avatar image }UI Behavior
While data is loading (
!data), a simple<h1>loading...</h1>message is shown.If logged in, user details and logout button are shown.
If not logged in, a prompt and login button are rendered.
Interaction with Other Parts of the System
../components/button
Provides theButtoncomponent for consistent styling and behavior of buttons on the page.../libs/fetch
Contains thefetchfunction that abstracts HTTP fetching logic, used by SWR to retrieve user data.../libs/auth
Includes theloginandlogoutfunctions that handle user authentication side effects, potentially redirecting to auth providers or clearing session tokens./api/userEndpoint
The component relies on this backend API to get the current user’s authentication status and profile information.SWR Library
Handles data fetching lifecycle and caching, allowing the UI to reactively update on authentication changes.
Visual Diagram
flowchart TD
A[Index Component] -->|calls| B(useSWR('/api/user', fetch))
B -->|fetches| C[/api/user Endpoint]
A -->|renders| D[UI: Loading | LoggedIn View | Login Prompt]
D --> E[Button Component]
E -->|onClick| F{login() or logout()}
F -->|trigger| B
subgraph External Dependencies
B
C
E
F
end
Diagram Explanation
The
Indexcomponent usesuseSWRto fetch user data from/api/user.The UI rendered depends on the data fetched.
The
Buttoncomponent is used for login/logout actions.Clicking buttons calls
login()orlogout(), which triggers SWR'smutate()to refresh the user data, updating the UI accordingly.
Summary
The index.js file is a simple but crucial component in the application that manages user authentication state presentation. It efficiently combines React, SWR data fetching, and authentication utilities to provide a responsive and seamless user login/logout experience. The clear separation of concerns and use of reusable utilities/components aligns with the project’s modular architecture and scalability goals.