'How to access a property in JSON from API request and display in React?
Background
I am currently trying to access the second property of a JSON file below named 'year_level'. I am doing this so that I can pass the data into an array and later display it in a react component for an autocomplete field. However, every time I try to write in the field, it crashes and gives me errors which do not really help me.
JSON
[{'prog_id': 'CDE', 'year_level': None}, {'prog_id': 'DDS1', 'year_level': '1'}, {'prog_id': 'DDS2', 'year_level': '2'}, {'prog_id': 'DDS3', 'year_level': '3'}]
Relevant Code
API request below that requires a join on 'prog_id' to access 'year_level':
@api_view(["GET"])
def retrieve_prog_ids(request):
progs = Event.objects.select_related('prog_id').values('prog_id').annotate(year_level=F('prog_id__year_level')).distinct()
list = []
for i in progs:
list.append(i)
print(list)
return JsonResponse(list, safe = False)
axios request to access data in frontend:
await axios({
method: "get",
url: "/events/prog-id/",
})
.then((res) => this.handleProgData(res.data))
.catch((err) => console.log(err));
tried using a handler to access the data from api request and get the 'year_level':
//Pushes year_levels into an array
handleProgData(prog_data) {
var programs = [];
for (var i = 0; i < prog_data.length; i++) {
programs.push(prog_data[i].year_level); //need 'year_level'
}
console.log(programs);
this.setState({ programs });
}
Errors
utils.js:31 Uncaught TypeError: Cannot read properties of null (reading 'label') //...1st error
The above error occurred in the <AutoComplete> component: //... 2nd error
utils.js:31 Uncaught TypeError: Cannot read properties of null (reading 'label') //...3rd error
Please let me know as to why it is crashing every time I type in the autocomplete field. I'm thinking it is not correctly accessing 'year_level' but I could be wrong. Thank you in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
