I’m working on a React app where I need to dynamically access different columns in my Airtable base. The columns have similar names but end with different numbers like ‘Task1’, ‘Task2’, etc.
My setup involves determining which week we’re in, then using that number to build the correct column name. For example, if we’re in week 3, I want to access the ‘Task3’ column.
The issue is that this.state.records[j].fields[currentWeek] needs to work to retrieve the dynamic field name based on the week number. I’ve tried various methods but keep hitting parsing errors. What should I do to access the correct Airtable field dynamically?
Had this exact problem last year with a project tracking app. Bracket notation works fine, but here’s the catch - Airtable sometimes returns field names with weird casing or formatting. First thing I’d do is fetch a sample record and log Object.keys(record.fields) to see exactly how the field names look. Also check if your currentWeekValue is a string or number. I got burned when the prop came through as “3” instead of 3, which broke everything. Make sure your records array actually has data when this runs too. I ended up adding a null check like this.state.records[j].fields[currentWeek] || '' since some records might not have that dynamic field.
Your approach looks right - this.state.records[j].fields[currentWeek] should work fine with bracket notation. I’ve done similar stuff with Airtable and React without problems. The parsing errors are probably coming from somewhere else. Check that your currentWeekValue prop is actually a number and not undefined when the component renders. Also make sure the Airtable records are fully loaded before this runs. I’d throw in some console.log statements to debug - log this.state.records[0].fields and currentWeek to see if the field names match exactly what Airtable returns. Sometimes there are random spaces or the field names don’t match what you expect.
Bracket notation should definitely work here. I’ve built similar features pulling data from different columns based on user selections or date calculations.
Timing usually trips people up though. Your code might run before Airtable data finishes loading. I wrap this logic in a check like:
if (!this.state.records || this.state.records.length === 0) {
return null;
}
Another issue I see is when the field doesn’t exist on some records. Airtable won’t return empty fields in the API response, so fields[currentWeek] returns undefined instead of an empty string. React complains about this.
Try logging the actual field structure first:
console.log('Available fields:', Object.keys(this.state.records[0].fields));
console.log('Looking for field:', currentWeek);
I bet you’ll find either the field names don’t match exactly or some records are missing that field entirely. Easy fix once you know what’s actually in there.