Async state — demo
User profile that re-fetches automatically whenever the selected userId changes. Shows how asyncState wires reactive dependencies into an async producer.
What it shows
- A
userId = state(1)signal. - A
profile = asyncState(async () => …)that readsuserIdinside the producer —asyncStatetracks the read, re-runs on change. - Companion
loading/errorsignals updated inside the producer (asyncStateonly models the value; surrounding state is yours). - A simple
<select>swap demonstrates the auto-refetch with nouseEffector dep array.
The logic
import { state } from '@react-logic/react-logic';
import { asyncState } from '@react-logic/utils';
class ProfileLogic {
userId = state(1);
loading = state(false);
error = state<string | null>(null);
profile = asyncState(async () => {
const id = this.userId();
this.loading(true);
this.error(null);
try {
const r = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return await r.json();
} catch (e) {
this.error(String(e));
return null;
} finally {
this.loading(false);
}
});
}
For HTTP-shaped fetching with built-in loading/error/status, see the Fetch state demo.
Run it
nx serve demo-async-state