[ Language & values ]
@sdxc/iife
Immediately invoke a callback where an expression is needed
- Used by
- uptime, auth-saas, reader, blog
- Source
- packages/iife
Immediately invoke a callback where an expression is needed.
Installation
npm add @sdxc/iife
Usage
Compute a value without an outer mutable binding
import { iife } from "@sdxc/iife";
let buttonLabel = iife(() => {
if (isSaving) return "Saving…";
if (hasChanges) return "Save changes";
return "Saved";
});
Branch in the middle of JSX
import { iife } from "@sdxc/iife";
<header>
<h1>{team.name}</h1>
<p>
{iife(() => {
if (team.plan === "enterprise") return "Priority support enabled";
if (team.trialEndsAt) return `Trial ends on ${formatDate(team.trialEndsAt)}`;
return "Standard support";
})}
</p>
</header>;
Keep try/catch inside the assignment
import { iife } from "@sdxc/iife";
let result = iife(() => {
try {
let data = JSON.parse(input) as { name: string };
return { data: data.name, error: null };
} catch {
return { data: null, error: "Invalid JSON input" };
}
});
Await sequential async work inline
import { iife } from "@sdxc/iife";
let viewer = await iife(async () => {
let response = await fetch("/api/viewer");
return response.json() as Promise<{ profileUrl: string }>;
});
let profile = await iife(async () => {
let response = await fetch(viewer.profileUrl);
return response.json();
});
API
iife<T>(fn: () => T): T
Runs fn immediately and returns its result. An async callback yields a promise; await it like any other.
Pattern: Object fields that need a branch
import { iife } from "@sdxc/iife";
let payload = {
title: "Invoice",
status: iife(() => {
if (isPaid) return "paid";
if (isOverdue) return "overdue";
return "pending";
}),
};