I'm trying to fetch a set of questions from a Firestore database, and then store them in a local array for use later on in a quiz. As I'm working to fetch the data, it's running asynchronously. I've dealt with this before, and the solution was a useEffect() hook and conditionally rendering component.
My code currently looks like this:
var questions = [];
var collection = useRef('Planning');
var [loading, setLoading] = useState(true);
useEffect(() => {
if (props.track === 'Testing & Deployment') {
collection.current = 'Test_Deploy';
} else {
collection.current = props.track;
}
if(questions.length !== 0){
setLoading(false)
} else {
var questionSet = db.collection('Quizzes').doc(collection.current).collection('Questions')
questionSet.withConverter(questionConverter).get().then(function(response) {
response.forEach(document => {
var question = document.data();
// running asynch - need to address
console.log('Question in')
questions.push(question)
})
})
setLoading(false)
}
}, [props.track, questions])}
Depending on where setLoading() is, the component either won't re-render at all, or will double fetch the data from Firestore. I've tried playing around with useCallback() to no avail, and have also seen that this might be an issue with React StrictMode.
Any advice on how to fix my code in order to re-render the page after fetching all of the questions, without double fetching them?