I am using react-query to make a GET request to my API in which the response is an array of objects. Each object has 1 property which is the name that I want to access. When I log the response to the console, it appears like the image listed at the bottom. However, when I try to access an element of the response, it says “cannot read properties of undefined”.
Here is the code which displays the data as shown in the image:
const { isLoading, error, data } = useQuery('cat_names', () =>
fetch('<api-link>').then(res =>
res.json()
)
)
console.log(data)
Here is the code I used to try accessing the first element of the array.
const { isLoading, error, data } = useQuery('cat_names', () =>
fetch('<api-link>').then(res =>
res.json()
)
)
console.log(data[0])
I have also tried mapping data, with no luck:
const mapped_data = data.map(element => element.name)
console.log(mapped_data)