T
TanStack•3y ago
implicit-lime

Why doesn't random value work here but static does?

Here's the code
const getRandomId = (numbers: Number[]) => {
return Math.floor(Math.random() * numbers.length)
}

const {
data: questionData,
refetch: refetchQuestion,
isLoading: isQuestionLoading,
isSuccess: isQuestionSuccess,
} = useQuestionWithAnswers(
unusedQuestionsIds.length > 0
? unusedQuestionsIds[getRandomId([1, 2, 3])]
: null
)
const getRandomId = (numbers: Number[]) => {
return Math.floor(Math.random() * numbers.length)
}

const {
data: questionData,
refetch: refetchQuestion,
isLoading: isQuestionLoading,
isSuccess: isQuestionSuccess,
} = useQuestionWithAnswers(
unusedQuestionsIds.length > 0
? unusedQuestionsIds[getRandomId([1, 2, 3])]
: null
)
This will keep me in the state of loading forever even tho the data is fetched. But if I remove the getRandomId function and just set the id statically it all works. At first I thought that there was a problem with my state management, but it seems like its Tanstack Query related. Also here's the custom hook for the useQuery that I created.
import { Answer, Question } from "@prisma/client"
import { useQuery } from "@tanstack/react-query"
import axios from "axios"

export interface QuestionWithAnswers extends Question {
answers: Array<Omit<Answer, "isCorrect">>
}

export const useQuestionWithAnswers = (questionId: number | null) => {
return useQuery({
queryFn: async () => {
try {
const { data } = await axios.get(`/api/quiz/question/${questionId}`, {
headers: { Accept: "application/json" },
})

return data
} catch (error) {
if (axios.isAxiosError(error)) {
throw new Error(error.message)
}

throw new Error("An unexpected error has occured")
}
},
queryKey: [`question-${questionId}`, questionId],
enabled: false,
})
}

export default useQuestionWithAnswers
import { Answer, Question } from "@prisma/client"
import { useQuery } from "@tanstack/react-query"
import axios from "axios"

export interface QuestionWithAnswers extends Question {
answers: Array<Omit<Answer, "isCorrect">>
}

export const useQuestionWithAnswers = (questionId: number | null) => {
return useQuery({
queryFn: async () => {
try {
const { data } = await axios.get(`/api/quiz/question/${questionId}`, {
headers: { Accept: "application/json" },
})

return data
} catch (error) {
if (axios.isAxiosError(error)) {
throw new Error(error.message)
}

throw new Error("An unexpected error has occured")
}
},
queryKey: [`question-${questionId}`, questionId],
enabled: false,
})
}

export default useQuestionWithAnswers
2 Replies
implicit-lime
implicit-limeOP•3y ago
Its worth noting that I'm using Next 13 with custom API routes 🙂
generous-apricot
generous-apricot•3y ago
It looks like you're switching between random numbers on every render. Put the random number in react state.

Did you find this page helpful?