import { PureComponent } from 'react'; import { profileAsyncAutomat } from '../automats/profileAsyncAutomat.js'; /** * AsyncApiPrimaryView โ Left column of Section 06. * * Demonstrates: * 1. Initial access to an asynchronous Automat: constructor calls `profileAsyncAutomat.getData()`. * 2. On first mount when data is not yet loaded, status is 'pending'. * 3. The component renders `pending` (Render #1). * 4. In `componentDidMount()`, it subscribes to updates. * 5. When the simulated API fetch completes, `setState` runs and the component renders again (Render #2). */ export default class AsyncApiPrimaryView extends PureComponent { _renderCount = 0; _constructorStatus = 'uninitialized'; constructor(props) { super(props); // 1. Initial read in constructor triggers the async loader if idle: this.state = profileAsyncAutomat.getData(); this._constructorStatus = this.state.status; } componentDidMount() { // 2. Subscribe to receive update when API fetch completes: this.unsubscribe = profileAsyncAutomat.subscribe(this); } componentWillUnmount() { if (this.unsubscribe) this.unsubscribe(); } handleReload = () => { profileAsyncAutomat.reload(); }; handleReset = () => { profileAsyncAutomat.actions.reset(); }; handleSimulateError = () => { profileAsyncAutomat.actions.triggerError(); }; handleDelayChange = (ms) => { profileAsyncAutomat.actions.setDelay(ms); }; render() { this._renderCount++; const { status, data, error, delayMs, fetchCount, lastFetchedAt } = this.state; return (
getData() will launch the delayed API request.
status: 'pending'. Rendering 1st pass.