I have a collection of football matches. I am calling a 3rd party API to update the scores. I can read the JSON response and write the scores to a console log, so I know that I’m fetching the data correctly. I can read/write to the item in the AfterQuery function so I know I have permissions set right. But once I’m in the fetch function, I can only read the item and write to console log. Any ideas on how I can write to the item?
I come from VBA so my Javascript knowledge is very basic. I’m sure there’s some very simple method to get this working. Any help is greatly appreciated.
Please post your code so we an see what you’re doing so far.
So after some intense Googling, I have half solved the issue. I’ve learnt all about async/await and this has helped me to get the JSON response into a collection.
export async function fetchStuff(URLToFetch) {
try {
const response = await fetch(URLToFetch);
const myJSON = await response.json();
const homeScore = await myJSON[“event”][0].intHomeScore;
const awayScore = await myJSON[“event”][0].intAwayScore;
return myJSON;
} catch (err) {
console.log(err);
}
}
export async function Matches_afterQuery(item, context) {
let hookcontext = context;
strURL = “https://www.thesportsdb.com/api/v1/json/1/searchfilename.php?e=English_Premier_League_2018-05-13_Huddersfield_Town_vs_Arsenal”
await fetchStuff(strURL).then((objJSON) => {
item.homeScore = parseInt(objJSON[“event”][0].intHomeScore, 10);
item.awayScore = parseInt(objJSON[“event”][0].intAwayScore, 10);
item.matchStatus = “Finished”;
return item;
})
}
Here’s an abbreviated version of my code.
I now run into the issue of not being able to add new items to the collection. I believe this is because I’ve turned the hook into an async function. When I comment the function out, the collection loads and I can add new items. I guess the workaround is to use a different hook or move the async to another function to be called.
The current API returns one particular match. However there is an API that can return all matches at once. I’d just need to go through the arrays in the returned JSON object to get the right match. I might decide to go down that route of returning all the matches and then looping my items after the API fetch and find the match I need that way. That’s probably better than an API fetch for every item in the collection, right?
Any help would be appreciated. If I figure it out myself, I will post the result here.