Reputation: 23
the content I fetch from my svelte store disappears on page refresh, is there a way to stop it from resetting so it can stay on the page even when i reload? sorry if the question is a little vague im not sure how to really phrase it.
svelte store
import { writable } from "svelte/store";
export const leagueTable = writable([]);
const fetchTable = async () => {
const url = `https://soccer.sportmonks.com/api/v2.0/standings/season/19734?api_token=API_KEY`;
const res = await fetch(url);
const data = await res.json();
leagueTable.set(data.data);
}
fetchTable();
component
<script>
import { leagueTable } from "../stores/league-standings-stores"
console.log($leagueTable)
const tableMaps = $leagueTable.map($leagueTable => $leagueTable.standings.data).flat();
console.log(tableMaps)
</script>
{#each tablePositions as tablePosition}
<div class="standings-table flex gap-9 mb-2 pb-4 pt-3 border-b border-[#303041]">
<div class="team-details flex gap-4 w-full" id="td">
<p class="w-[18px]">{tablePosition.position}</p>
<img src="{tablePosition.team.data.logo_path}" alt="" class="w-[1.5em] object-scale-down">
<p class="">{tablePosition.team_name}</p>
</div>
<div class="team-stats flex gap-5 text-left child:w-5 child:text-center w-full">
<p>{tablePosition.overall.games_played}</p>
<p>{tablePosition.overall.won}</p>
<p>{tablePosition.overall.draw}</p>
<p>{tablePosition.overall.lost}</p>
<p>{tablePosition.overall.goals_scored}</p>
<p>{tablePosition.overall.goals_against}</p>
<p>{tablePosition.total.goal_difference}</p>
<p>{tablePosition.overall.points}</p>
<p class="!w-[78px] !text-left">{tablePosition.recent_form}</p>
</div>
</div>
{/each}
Upvotes: 2
Views: 3182
Reputation: 129
Use github.com/joshnuss/svelte-local-storage-store
npm install svelte-local-storage-store
Then, inside your store page, usually a js file:
import { persisted } from 'svelte-local-storage-store'
export const leagueTable = persisted('leagueTable', [])
In your svelte page you can use it as:
import {leagueTable} from './stores'
Use as you wish
leagueTable.subscribe(...) // subscribe to changes
leagueTable.update(...) // update value
leagueTable.set(...) // set value
get(leagueTable) // read value
$leagueTable // read value with automatic subscription
Upvotes: 0
Reputation: 311
Check if localstorage data exists:
let localData = localStorage.getItem("leagueTable")
export const leagueTable = writable(localData ? JSON.parse(localData) : []);
Save to local storage and keep in sync with store:
$: {
localStorage.setItem("leagueTable", JSON.stringify($leagueTable))
}
Upvotes: 2