When I do this, the code works.
console.log(characters.data.results[2])
I would obviously get the third object in the array. but this is static. I want it to be randomized so I did this.
console.log(Characters.data.results[Math.floor(Math.random() * 21)])
it didn't work, I keep getting this error
Main.jsx:6 Uncaught TypeError: Cannot read properties of undefined (reading 'results')
at Main (Main.jsx:6:1)
at renderWithHooks (react-dom.development.js:16175:1)
I even made the code cleaner by doing
const random = Math.floor(Math.random() * 21);
console.log(characters.data.results[random])
but I got the same error. What am I doing wrong? I am new to react.
The value of Characters.data is undefined on first render and maybe changing afterwards.
To make sure Characters.data is not undefined before accessing Characters.data.results. You can use optional chaining (?.)
console.log(Characters.data?.results[Math.floor(Math.random() * 21)])