0

I am writing a web application showing departures from a preselected station. An id of the selected station is saved as a coockie. A JSON file containing id's and full names is read into an array with the id's as keys and full names as values, like this Stations[Id] = FullName. This works just fine when writing to console but not to the html page when it is opened or reloaded, the checkCoockie()function. It says undefined instead of the station. After a new station has been chosen the stations full name is shown properly, the setCoockie()function.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>

var Stations = [];

function onLoad() {
    checkCookie();
    return;
}

async function loadStations() {
    fetch("tinystations.json")
        .then(response => response.json())
        .then(stations => stations.forEach(item => 
            Stations[item.Id] = item.FullName));
        return;
}

async function checkCookie() {
    await loadStations();
    console.log(Stations);
    var station1 = getCookie("station1");
    document.getElementById("chosen1").innerHTML = station1 + " : " + Stations[station1];
    return;
}

function setCookie() {
    const d = new Date();
    d.setTime(d.getTime() + 100000000000); // Sufficiant amount of time. 3 years.
    let expires = "expires=" + d.toUTCString();
    let station1 = document.getElementById("TIstation1").value;
    document.cookie = "station1=" + station1 + ";" + expires;
    document.getElementById("chosen1").innerHTML = station1 + " : " + Stations[station1];
    return;
}

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}
</script>
</head>
<body onload="onLoad()">
    <div id="coockie">
        <p>Select new stations</p>
        <input id="TIstation1" type="text" placeholder="Choose station" />
        <button onclick="setCookie()">Save</button>
    </div>
    <div id="chosen">
        Preselected:
        <p id="chosen1"> </p>
    </div>
</body>
</html>

This is my JSON file:

[
    {
        "FullName": "Arlanda C",
        "Id": "Arnc"
    },
    {
        "FullName": "Huddinge",
        "Id": "Hu"
    },
    {
        "FullName": "Jakobsberg",
        "Id": "Jkb"
    },
    {
        "FullName": "Stuvsta",
        "Id": "Stu"
    },
    {
        "FullName": "Rotebro",
        "Id": "R"
    },
    {
        "FullName": "Stockholm City",
        "Id": "Sci"
    }
]

When opening or reloading page it look like this: When opening or reloading page

And after a new station been chosen and new coockie set: enter image description here

I thought the Stationsarray might not be ready when checkCoockie() was executed so I made checkCoockie() async and made it wait for loadStations() to finish. That didn't help. I have tried many async/await solutions the last month but none have helped. Any suggestions how I can get this to work on page load?

2
  • 1
    loadStations doesn't need to be async since you're not awaiting anything. Technically you just need to return fetch() and things should work... I'd suggest though that you remove the global Stations variable and instead return a new stations object form your .then() and then use const stations = await loadStations() when calling loadStations. Commented Feb 4, 2024 at 23:07
  • @NickParsons Thanks for your comment. Returning Stations as a function value has crossed my mind but I rather not go that way. I don't see how I can use Stations in the setCoockie function. That function is called when I push a button. And I'd prefer not to read the JSON file again. It is not huge but still around 50kb. Another reason is that I set another array in the loadStations, not shown in this example because it's working and I wanted to cut out all that's not relevant. I have to give up on this. It's annoying me though, that I can't figure out why it's not working. Commented Feb 5, 2024 at 17:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.