I have a fetch that calls an API and adds all of the records to my table (Title, Date, Unique ID). That is good.
Now when I make another call to the API I want to run thought the existing field, match the Unique ID and update the name and date (does not matter if they are different) and if there is no record with that Unique ID add the Title, Date and Unique ID to the end of the records.
let response = await remoteFetchAsync("URL", requestOptions);
let json = await response.json();
let table = base.getTable("Table");
let titleColumn = table.getField("Title")
for (i=0; i < json.length; i++) {
if(json[0].Title !== titleColumn){
let recordId = await table.createRecordAsync({
"Title": json[i].Title,
"Date": json[i].Date,
"Unique ID": json[i].uniqueID
})
}
};
Hey man, here’s a working copy of my attempt at it
(Edited to add: The code that follows is not as good as it should be, and a newer version can be found two replies later that incorporates the suggestions and fixes that kuovonne provided! Please scroll down and use that one instead!)
Code below:
let table = base.getTable('Table 1')
let newData = [
{
title: 'Title 4',
date: 'Date 4',
uniqueID: 'unique4'
},
{
title: 'New Title 1',
date: 'New Date 1',
uniqueID: 'unique1'
}
]
let query = await table.selectRecordsAsync({
fields:['Unique ID']
})
let existingUniqueIDs = new Object
for (let record of query.records){
let uniqueID = record.getCellValue('Unique ID')
existingUniqueIDs[uniqueID] = record.id
}
for (let data of newData){
if(existingUniqueIDs[data.uniqueID]){
table.updateRecordAsync(existingUniqueIDs[data.uniqueID],{
"Title": data.title,
"Date": data.date
})
}
else{
await table.createRecordAsync({
"Title": data.title,
"Date": data.date,
"Unique ID": data.uniqueID
});
}
}```
Adam, I like seeing other people’s code. Your code is very similar to how I would do it, with a some exception. (1) I would batch the record updates and record creation. (2) I would use the await keyword when updating records (but this may be a typo).
You don’t need the if statement. It has the same condition as the while. The condition for a while loop is tested before the first iteration of the loop is executed.
Ahh! Thank you for pointing that out! I’ve edited the script above
I really can’t put into words how much I appreciate you taking the time to tell me both about the places where I can improve as well as the logic behind it. Thank you very very much for doing all of this