I'm randomizing the answers for my quiz app. It does randomizing the answers but when any answer is selected, it randomize the answers again.
{questions[currentQuestion].options
.slice(0, questions[currentQuestion].options.length - 1)
.sort(() => Math.random() - 0.5)
.map((answer, index) => (
<TouchableOpacity
onPress={selectedAnswerHandler.bind(
this,
answer.id,
answer.answerText
)}
key={index}
>
<View
style={
selectedAnwserId === answer.id
? styles.selectedAnswerTab
: styles.answerTab
}
>
<Text
style={
selectedAnwserId === answer.id
? [styles.answerText, { color: color.secondaryColor }]
: styles.answerText
}
>
{answer.answerText}
</Text>
</View>
</TouchableOpacity>
))}
Here is the selectedAnswerHandler
const selectedAnswerHandler = (ansId, answer) => {
setSelectedAnswerId(ansId);
setSelectedAnswer(answer);
};
I know its randomizing again because state is changing and its re-rendering. How can I prevent this?
CodePudding user response:
Learn useEffect and its dependency array. for eg.
Well, this may not be the exact correct answer but will give a clear idea.
useEffect(()=>{
selectedAnswerHandler(ansId, answer)
},[ansId, answer])
this will only call selectedAnswerHandler when either one of ansId, answer changes. ansId, answer can be your state or anything.
CodePudding user response:
This is because you're passing the index
of iteration to the key
prop. If you recreate the array, all the questions get shuffled, and assigned to new indexes, which trashes a bunch of render state.
If you provide each question with a unique key
attribute and use this as the key
prop, regardless of how you shuffle the questions will still render gracefully.