Issue
Every time I run the nextQuestion, the questions change. it's like running the whole function again, but the nextIndex is not reset.I understand this because I see the category appear several times
import React, { useState } from 'react';
import { useLocalSearchParams } from "expo-router";
import { COLORS } from "../constants";
import { View, Text, Image, Button, StyleSheet, SafeAreaView } from "react-native";
import { requestQuestions } from "../constants/support";
import Header from '../constants/testHeader';
const Test = () => {
const { category } = useLocalSearchParams();
let questions = requestQuestions(category);
const [currentQuestion, setCurrentQuestion] = useState(0);
console.log(category)
const nextQuestion = () => {
const nextIndex = (currentQuestion + 1) % questions.length;
if (nextIndex === 0) {
alert('All question are finished.');
} else {
setCurrentQuestion(nextIndex);
}
};
const { id, img, question, anwsers } = questions[currentQuestion];
console.log(questions.map(obj => Object.values(obj)[0]), currentQuestion)
return (
<SafeAreaView style={styles.area}>
<Image source={img || { uri: "https://www.liaros-drive.gr/test/images/pic0484.jpg" }} style={styles.image} />
<Text style={styles.title}>{question}</Text>
<SafeAreaView style={styles.buttonContainer}>
{
anwsers && anwsers.map((anwser, index) => (
<Button key={index} title={`${index+1}) (${anwser})`} onPress={nextQuestion} />
))
}
</SafeAreaView>
</SafeAreaView>
)
}
export default Test;
support.js the questions it is a array of objects.
import { sampleSize } from 'lodash';
import { questions } from './questions.json';
export const requestQuestions = (category = "random") = \ > {
console.log('test')
if (category == "random") {
return sampleSize(questions, 10)
} else {
return sampleSize(questions.filter(x = \ > x.category == category), 10)
}
}
Solution
Every time you call a setter of a state property inside a React component, the component function is called again - in this case calling requestQuestions
again, yielding a new list of questions.
Solution: pass the questions as a prop to Test
to keep them the same:
function Test({ questions }) {
const [currentQuestion, setCurrentQuestion] = useState(0);
// ...rest of your component
}
and in the parent component:
const { category } = useLocalSearchParams();
const questions = requestQuestions(category);
...
return (
...
<Test questions={questions}/>
...
)
Answered By - moonwave99
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.