CodingNic

Application State and Navigation

Create Shared Converter State

Application State and Navigation 12 min read

Create Shared Converter State

Create Shared Converter State

Stay in app.js, directly below the currency data.

The project uses a small set of shared variables rather than a framework state library. Create the same state model used by the application:

javascript
let rates = { ...fallback };
let from = "USD";
let to = "EUR";
let range = "1D";
let live = false;

Then add two tiny helpers:

javascript
const $ = id => document.getElementById(id);
const rate = (a, b) =>
  a === b ? 1 : (rates[b] ?? fallback[b]) / (rates[a] ?? fallback[a]);

The important detail is that every page view will read the same from and to values.

Test it

Open DevTools and run from, to, and rate("USD", "EUR"). You should see USD, EUR, and the fallback USD/EUR calculation.

Checkpoint

Changing from or to in the console should change what rate(...) returns. Nothing else needs to be interactive yet.