I have an array of object and I need to get a single property, but it's returning undefined and have no idea why. Does anyone know how to solve?
const [questions, setQuestions] = useState({});
const [index, setIndex] = useState(0);
async function handleQuestions() {
const fetchQuestions = await fetchTriviaApi();
setQuestions(fetchQuestions.results);
}
useEffect(() => {
handleQuestions();
}, []);
Return of questions:
(5) [{…}, {…}, {…}, {…}, {…}]
0: {category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg's real name is 'Cordozar Calvin Broadus, Jr.'.', correct_answer: 'True', …}
1: {category: 'Entertainment: Video Games', type: 'multiple', difficulty: 'medium', question: 'Which of these "Worms" games featured 3D gameplay?', correct_answer: 'Worms 4: Mayhem', …}
2: {category: 'Vehicles', type: 'multiple', difficulty: 'easy', question: 'What UK Train does NOT go over 125MPH?', correct_answer: 'Sprinter', …}
3: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'medium', question: 'Tony Hawk's Pro Skater was released in 1999.', correct_answer: 'True', …}
4: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'hard', question: 'In The Witcher 3, the Zoltan Chivay Gwent card can be found under the Hanged Man's Tree.', correct_answer: 'True', …}
length: 5
Return of questions[index]:
{category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg's real name is 'Cordozar Calvin Broadus, Jr.'.', correct_answer: 'True', …}
Return of questions[index].category: When I try to access any property it returns undefined.
CodePudding user response:
You need to initialize the questions
state to an empty array.
const [questions, setQuestions] = useState([]);
And when accessing the items you have to check whether the questions
is populated by the API call.
{questions.length > 0 && questions[index].category}
CodePudding user response:
Most likely your fetch is not being awaited properly. You need to wait for the json() as well. And remember setState is asynchronous and not immediate. Only on next rerender will you be sure to have data changed.
CodePudding user response:
Maybe because you're initializing your questions state as an object so questions[1] is indeed undefined as soon as handleQuestions is resolved.
CodePudding user response:
I believe you should map though the array of objects.
let results = questions.map(item => item.category)
Hope this helps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map