Problem reading JSON values from file into array in javascript

46 Views Asked by At

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?

0

There are 0 best solutions below