Skip to main content
Frontend tutorial

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.

Work locally

You need Node.js 24, pnpm and Git (how to set them up). Clone this step’s starting code:

git clone --depth 1 \
--branch lesson-07-03-store-start-v6 \
https://github.com/adam-zielonka/frontend-tutorial.git \
07-03-store
cd 07-03-store
pnpm install --frozen-lockfile
pnpm dev

To keep your own commits: git switch -c my-work.

Browse the source on GitHub (opens in a new tab)

Bring your browser edits

Choose Download my files in the ⋯ menu. It saves the lesson’s files as JSON. Stop the local server with Ctrl+C, copy the download into the project folder and run:

node import-draft.mjs ./07-03-store-my-files.json
pnpm dev

The import replaces the project’s exercise files, so commit or back up local edits first.

Loading this step’s code…
Starting the live preview…