I'm fetching async object with an array and a value. I want to take the array and add that other value to the same array at a random index.
{
incorrect_answers: ['item1', 'item2', 'item3'],
correct_answer: 'item4'
}
// I expect this: ['item1', 'item2', 'item4', 'item3'] the index for 'item4' is random
I get the array with useState fine, but don't know how to add the other value in the same useState line:
const [index, setIndex] = useState(0);
const [answers, setAnswers] = useState([]);
useEffect(()=>{
(async () => {
const data = await fetch ('https://opentdb.com/api.php?amount=10&type=multiple');
const json = await data.json();
setAnswers(json.results[index].incorrect_answers);
//if I use .splice here, I get only the correct_answer in the array
answers.splice(random,0, json.results[index].correct_answer);
setAnswers(answers)
})();
}, []);
UPDATE:
the complete project is here: https://codepen.io/metsuge/pen/qBxyrMY The idea is that when clicking Next Question, the index would update to show the next object in the array. But the index value in NextQuestion() and in the if statement is off by 1, so questions and answers are mixed
setAnswermay point to the oldanswersarray as callingsetAnswercan async.setAnswerscalls and will only call the 2ndsetAnswer. So yourincorrect_answerswill never set to theanswersarray. Therefore you are actually splicing the initial empty array.incorrect_answersbefore insert thecorrect_answerand still usesanswers.splice, then the original data will be mutate. So after you mutate the original data set, you call thesetAnswers(answers)with mutated data. When react compares the old value to the new value provided insetAnswersit sees both are equal. So React will ignore state update.How you can fix the issue
References
UPDATE
I have update your
QuizeComponent