I have json file which i load and i use Hook to SetState to it. After SetState i want to use state with Value of Json to my function. But my function is executing with null value because setState doesnt load before Execute function. Here is code
const fetchQuestions = async () => {
const data = await require("../../question.json");
await setQuestions(
data.map((item: IQuestion) => ({
id: item.id,
question: item.question,
answers: item.answers
})
))
await setQuestionsArray(
data.map((item: IQuestion) => ({
id: item.id,
name: item.question
})
))
return questionsArray
}
There is Function which i pass questionArray :
const handleQuest = (array: Array<IArrayQuestion>) => {
if (array.length > 0) {
const numberArray = array.length
const random = Math.floor(Math.random() * (numberArray - 0))
const p = (array[random])
setQuestion(p.name)
setShuffleRandom(!shuffleRandom)
}
}
And i use it in useEffect
useEffect(() => {
if (nick.length < 1) {
navigate('/quiz')
}
fetchQuestions().then((res)=>{
if (questionsArray.length > 0){
handleQuest(res)
}
else{console.log("Nothing")}
})
}, [])
It still doesnt work. I dont have value in my function after promise