Tell us what’s happening:
I’m working on the Random Quote Machine. I created an array with several nested arrays acting as placeholders for quotes and their authors, which I am trying to separate by accessing the positions inside the nested array. However, this is causing an error. I’m not sure why, as this works using regular JavaScript, but if the first array value exists in component state, it doesn’t work.
undefined is not an object (evaluating 'quotes[this.state.generatedNumber][0]')
There’s also a message in the console about error handling:
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
in Unknown
but that just seems like something you do in case an error is thrown, and wouldn’t actually fix the error, just fallback on other UI. However, if I am misinterpreting and this is the root issue, please let me know.
That is where the problem is. When the component is mounted, the value of this.state.generatedNumber is "". Therefore, the value of quotes[this.state.generatedNumber] is undefined initially. And undefined[0] throws an error.
You need to first initialize the value of this.state.generatedNumber with a valid index. For example, you can set its value to 0 initially and generate a random index in one of the life cycle methods.