Loading api using a store in svelte pulls the data only when toggling using nav links

1.3k Views Asked by At

Using a store to fetch the an api the data does not load upon page reload. However by visiting the About page then by clicking the Home Nav link it does load the objects once then it seems to not allow to be modified.

import {nfl} from "../stores/nflstore";
 
console.log($nfl);

In the store

import { writable } from 'svelte/store';

export const nfl = writable([]);

const fetchNfl = async () => {
    const url = `https://api.sportsdata.io/v3/nfl/odds/json/LiveGameOddsByWeek/2020/2?key=`;
    const res = await fetch(url);
    const data = await res.json();
    
    const loadedData = data.map((data, index) => {
        return {
            isSelected: false,
            isSelectedAsParly: false,
            isSelectedAsTease: false,
            valueHomeSpread: false,
            valueAwaySpread: false,
            valueOverUnder: false,
            id: index + 1,
            away: data.AwayTeamName,
            away_spread: data.LiveOdds[0].AwayPointSpread,
            home: data.HomeTeamName,
            home_spread: data.LiveOdds[0].HomePointSpread,
            away_money_line: data.LiveOdds[0].AwayMoneyLine,
            home_money_line: data.LiveOdds[0].HomeMoneyLine,
            over_under: data.LiveOdds[0].OverUnder,
        };
        
    });
    nfl.set(loadedData);
};
fetchNfl();
1

There are 1 best solutions below

1
On

Generally, code in a module is only run once. So the fetch will happen once when the store code is loaded and the store value will not change until a hard page reload happens (possibly that is what you are referring to with "nav links").

What to do about this depends on the specifics of the application. E.g. you could export fetchNfl and call that in various places to fetch new data. The question then is whether the store is even required at all.

If you want to pass state between components it might be better to use setContext/getContext or just plain component properties. (You can also put the store in a context/property if necessary.)