I am making a recipe app with react and am incorperating a button to load more results at the bottom of the page. I have a data structure that looks like:
const data = [
[_links: {...}, hits:{...}],
[_links: {...}, hits:{...}],
[
_links: {
next: {
title: "Next",
href: "*endPoint*"
}
},
hits: {...}
]
]
When the button at the bottom of the component is clicked it adds the newly fetched data to the data array with the previous fetch. I want to grab the href that’s nested in the _links object from the last array inside the data array.
I am using a variable to grab it like:
const nextPage = data[data.length - 1]._links.next.href
When I console log nextPage I get what I am expecting, but I keep getting Uncaught TypeError: Cannot read properties of undefined (reading '_links') that’s breaking the page.
What is the correct way to grab the href from the last array in the data array?
>Solution :
data is an array of arrays of objects,
You can use Array.prototype.flat() to have 1 level of array and then Array.prototype.at() and get the last index of the array:
const data = [
[{_links: {}, hits:{}}],
[{_links: {}, hits:{}}],
[{
_links: {
next: {
title: "Next",
href: "*endPoint*"
}
},
hits: {}
}]
]
console.log(data.flat().at(-1)._links.next.href);
Array.prototype.at()
Array.prototype.flat()