Skip to main content

Hooks

The UI wire provides React hooks that connect to all FluxKit backend wires.

Authentication Hooks

useAuth()

Manages authentication state.

import { useAuth } from "@fluxkitdev/ui";

function Profile() {
const { user, loading, error, login, logout, register } = useAuth();

if (loading) return <div>Loading...</div>;
if (!user) return <div>Not logged in</div>;

return (
<div>
<h1>Welcome, {user.name}</h1>
<p>{user.email}</p>
<button onClick={logout}>Logout</button>
</div>
);
}

Return Value

PropertyTypeDescription
userUser | nullCurrent user or null
loadingbooleanAuth state is loading
errorError | nullLast auth error
tokenstring | nullCurrent JWT token
login(email, password)Promise<User>Log in
register(data)Promise<User>Create account
logout()Promise<void>Log out
refresh()Promise<void>Refresh user data

useOAuth()

Handle OAuth authentication flows.

import { useOAuth } from "@fluxkitdev/ui";

function OAuthButtons() {
const { loginWith, loading } = useOAuth();

return (
<div>
<button onClick={() => loginWith("google")} disabled={loading}>
Continue with Google
</button>
<button onClick={() => loginWith("github")} disabled={loading}>
Continue with GitHub
</button>
</div>
);
}

Data Hooks

useCollection(collection)

CRUD operations on a Store wire collection.

import { useCollection } from "@fluxkitdev/ui";

function ProductList() {
const { data, loading, error, create, update, remove, refetch } =
useCollection("products", {
sort: "-createdAt",
limit: 20,
});

if (loading) return <div>Loading...</div>;

return (
<ul>
{data.map((product) => (
<li key={product._id}>
{product.name} - ${product.price}
<button onClick={() => remove(product._id)}>Delete</button>
</li>
))}
</ul>
);
}

Options

OptionTypeDefaultDescription
filterobject{}MongoDB filter
sortstring-createdAtSort field
limitnumber20Page size
autoFetchbooleantrueFetch on mount

useDocument(collection, id)

Read and update a single document.

import { useDocument } from "@fluxkitdev/ui";

function ProductDetail({ id }: { id: string }) {
const { data, loading, update } = useDocument("products", id);

if (loading) return <div>Loading...</div>;

return (
<div>
<h1>{data.name}</h1>
<button onClick={() => update({ price: data.price + 1 })}>
Increase Price
</button>
</div>
);
}

File Hooks

useUpload()

Handle file uploads to the Store wire.

import { useUpload } from "@fluxkitdev/ui";

function AvatarUpload() {
const { upload, uploading, progress, error } = useUpload();

const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files[0];
const result = await upload(file, { metadata: { type: "avatar" } });
console.log("Uploaded:", result.url);
};

return (
<div>
<input type="file" onChange={handleFile} />
{uploading && <progress value={progress} max={100} />}
</div>
);
}

Messaging Hooks

useMessaging()

Send messages via the Messaging wire.

import { useMessaging } from "@fluxkitdev/ui";

function ContactForm() {
const { sendEmail, sending, error } = useMessaging();

const handleSubmit = async () => {
await sendEmail({
to: "support@example.com",
subject: "Contact Form",
body: "<p>Hello from the contact form</p>",
});
};

return (
<button onClick={handleSubmit} disabled={sending}>
Send Message
</button>
);
}

Payment Hooks

usePayment()

Handle payments via the Pay wire.

import { usePayment } from "@fluxkitdev/ui";

function BuyButton() {
const { createCheckout, loading } = usePayment();

const handleBuy = async () => {
const session = await createCheckout({
items: [{ name: "Pro Plan", amount: 2999, currency: "usd" }],
successUrl: window.location.href + "?success=true",
cancelUrl: window.location.href,
});
window.location.href = session.url;
};

return (
<button onClick={handleBuy} disabled={loading}>
Buy Pro Plan
</button>
);
}

Utility Hooks

useApi()

Make direct API calls to your FluxKit backend.

import { useApi } from "@fluxkitdev/ui";

function CustomComponent() {
const api = useApi();

const fetchData = async () => {
const response = await api.get("/custom/endpoint");
console.log(response.data);
};

const postData = async () => {
await api.post("/custom/endpoint", { key: "value" });
};

return <button onClick={fetchData}>Fetch Data</button>;
}

useColorMode()

Toggle between light and dark mode.

import { useColorMode } from "@fluxkitdev/ui";

function ThemeToggle() {
const { colorMode, setColorMode, toggleColorMode } = useColorMode();

return (
<button onClick={toggleColorMode}>
Currently: {colorMode}
</button>
);
}

useToast()

Show notification toasts.

import { useToast } from "@fluxkitdev/ui";

function SaveButton() {
const toast = useToast();

const save = async () => {
try {
await saveData();
toast.success("Saved successfully!");
} catch {
toast.error("Failed to save.");
}
};

return <button onClick={save}>Save</button>;
}