I’m new to JavaScript and working on an AirTable project. I’m trying to get info from an API call and update my AirTable. The tricky part is getting the most recent vote data, which is the last object in the ‘votes’ array.
Here’s what I’ve got so far:
let apiToken = 'my_secret_token'
let table = base.getTable('Test Bills')
let { records } = await table.selectRecordsAsync()
for (let record of records) {
let response = await remoteFetchAsync(`https://api.example.com/?key=${apiToken}&op=getInfo&id=${record.name}`)
let info = await response.json()
console.log(info.data)
// This part isn't working
const lastVoteInfo = info(info.votes.length - 1)
}
I’m stuck on two things:
How do I correctly set the lastVoteInfo variable?
Is there a better way to grab the last object in an array?
I’m getting this error:
TypeError: Can't read undefined (reading 'length')
at main on line 24
I’ve encountered similar challenges with AirTable and API integrations. Your approach is on the right track, but there’s a small issue in your code. The error suggests you’re trying to access ‘votes’ directly on ‘info’ instead of ‘info.data’.
This checks if votes exist b4 accessing. Also, u can use .pop() for the last item if u don’t need the original array anymore. Good luck with ur project!
I’ve been in a similar situation with AirTable projects. One thing to consider is error handling for your API calls. Sometimes the API might not return the expected structure, causing issues down the line.
For your specific problem, you could try using the optional chaining operator (?.) along with the nullish coalescing operator (??). It might look something like this:
This approach safely accesses nested properties and gracefully handles cases where the votes array might be empty or undefined. It’s a bit more robust and can save you from unexpected errors.
Also, don’t forget to implement some form of error logging. It’s invaluable when debugging these kinds of issues in production environments.