7.3. Fixing store
Open the Console. MobX complains that we changed ramps outside an action. init is an action, but the code after await runs later, when the action is already over. runInAction wraps those changes.
Now misspell RAMPS.json in /api.ts. GitHub answers with a real 404, and the preview shows a red error box. That box is for us, the developers. A user would only see an empty board, and for them an empty board means no ramps, which isn't true. The store has to remember more than the ramps: is it still loading, and did it fail?
import { makeAutoObservable, runInAction } from 'mobx';
export class Store {
ramps: Ramp[] = [];
status: 'loading' | 'error' | 'done' = 'loading';
error = '';
// ...
init = async () => {
this.status = 'loading';
try {
const ramps = await api.getRamps();
runInAction(() => {
this.ramps = ramps;
this.status = 'done';
});
} catch (error) {
runInAction(() => {
this.status = 'error';
this.error = String(error);
});
}
};
}
App shows both states. Retry just calls init again:
function App() {
const { ramps, status, error, init } = store;
return <div className="App">
<header className="Header">
<h1>ShippingBoard Lite</h1>
</header>
{status === 'loading' && <p className="Message">Loading ramps…</p>}
{status === 'error' && <p className="Message" role="alert">
Could not load the ramps. {error}
<button onClick={init}>Retry</button>
</p>}
<main className="Content">
{ramps.map(ramp => (
<section key={ramp.id} className="Ramp">
<header>{ramp.description}</header>
</section>
))}
</main>
</div>;
}
Need a hint?
- Misspell RAMPS.json in /api.ts to get a real 404 from GitHub.
- Retry is just onClick={init}.
Keep the wrong name: the board now says what happened, and Retry asks GitHub again. Fix the name and the ramps are back.