Skip to content
Advertisement

Wait Until Data is Fetched from MongoDB React JS

I’m creating a Quiz App. This is the Quiz Page Code. Quiz DB Document contains a QuizQuestions Array which has question ids. Then I fetch specific question from MCQ/Question DB. Fetching MCQ takes time and when I console.log fetched data. First and second time data in undefined then its viewable. Due to this I’m unable to display it as it cause TypeError: Cannot read properties of undefined mcqOptions How can I fix this?enter image description here `

JavaScript

Advertisement

Answer

The reason you’re getting undefined for the first and second time is due to the fact that useEffect would’ve not been executed by then. useEffect runs when the component is rendered and mounted for the first time, and then subsequent executions are made when there is a change in dependency array (If there are any dependencies). You could get rid of the error by rendering the dynamic content conditionally, i.e, displaying it when the data has been fetched.

JavaScript

Alternatively, if your mcqOptions is an array of objects you can map it accordingly, for instance, something like this,

JavaScript
Advertisement