Reputation: 604
I'm trying to figure out routing and responsiveness in Svelte. I have a very simple REPL set up: https://svelte.dev/repl/e366816d12d04fb4ac982b7c37058655?version=3.47.0
my App file specifies my routes. I just want to pass the name of a state into the path each time. That works fine.
<script>
import Router from 'svelte-spa-router';
import State from './State.svelte'
const routes = {
"/state/:stateName": State,
}
</script>
<ul>
<li><a href="/#/state/California">California</a></li>
<li><a href="/#/state/Idaho">Idaho</a></li>
<li><a href="/#/state/Montana">Montana</a></li>
<li><a href="/#/state/Oregon">Oregon</a></li>
<li><a href="/#/state/Washington">Washington</a></li>
</ul>
<Router {routes}/>
In State.svelte, I export params so that I can print the state name that I passed in. However, I also want to show some other data.
The way I have it set up now, currentPop shows up correctly when I click on the first state, but then as I click through the other states, that population number remains the same. How can I update my code so that the population is responsive? Thanks!
<script>
export let params;
import * as d3 from "d3";
let states = [{"ID State":"04000US06","State":"California","ID Year":2019,"Year":"2019","Population":39512223,"Slug State":"california"},{"ID State":"04000US16","State":"Idaho","ID Year":2019,"Year":"2019","Population":1787065,"Slug State":"idaho"},{"ID State":"04000US30","State":"Montana","ID Year":2019,"Year":"2019","Population":1068778,"Slug State":"montana"},{"ID State":"04000US41","State":"Oregon","ID Year":2019,"Year":"2019","Population":4217737,"Slug State":"oregon"},{"ID State":"04000US53","State":"Washington","ID Year":2019,"Year":"2019","Population":7614893,"Slug State":"washington"}]
let currentState, currentPop;
for(i=0;i<states.length;i++){
currentState = states.filter((d) => d.State == params.stateName);
currentPop = currentState[0].Population;
}
</script>
<p>
the great state of {params.stateName}
</p>
2019 population: {currentPop}
Upvotes: 0
Views: 1079
Reputation: 185445
Just make the update part responsive using $
:
$: for(i=0;i<states.length;i++) { //...
Svelte will track the dependencies of the statement/block and execute it again if any of the dependencies change.
The code can be simplified to this, by the way:
$: currentState = states.find((d) => d.State == params.stateName);
$: currentPop = currentState.Population;
Upvotes: 1