T
TanStack3y ago
afraid-scarlet

Shuffle array in dependent query forever loop

Hi guys, I have this query:
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}

export const useVariantQuery = (initialRecord, id) => {
const variantQuery = useQuery({
queryKey: ["variant", id],
queryFn: () => fetchVariant(id),
initialData: initialRecord,
initialStale: true,
})

const similarVariantIds =
variantQuery.data.fields.same_sub_category_variant_ids || []

const selectedIds = shuffleArray(similarVariantIds).slice(0, 12);

const { status, data: similarProductsQuery } = useQuery({
queryKey: ["similarProducts", similarVariantIds],
queryFn: () => fetchRecommendedVariants(selectedIds),
enabled: !!selectedIds.length,
})

return {
variantQuery,
similarProductsQuery,
similarProductsStatus: status,
}
}
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}

export const useVariantQuery = (initialRecord, id) => {
const variantQuery = useQuery({
queryKey: ["variant", id],
queryFn: () => fetchVariant(id),
initialData: initialRecord,
initialStale: true,
})

const similarVariantIds =
variantQuery.data.fields.same_sub_category_variant_ids || []

const selectedIds = shuffleArray(similarVariantIds).slice(0, 12);

const { status, data: similarProductsQuery } = useQuery({
queryKey: ["similarProducts", similarVariantIds],
queryFn: () => fetchRecommendedVariants(selectedIds),
enabled: !!selectedIds.length,
})

return {
variantQuery,
similarProductsQuery,
similarProductsStatus: status,
}
}
Withouth the shuffle, everything is OK. But if I ad the shuffle to similarVariantIds array, it load forever. How can I fix this?
1 Reply
extended-salmon
extended-salmon3y ago
Hi there. The order of items in the array matters, so when RQ stringifies similarVariantIds to use it as a queryKey by using shuffleArray you will get different results each time. This means that every time the query will re-run. You might consider making similarVariantIds an object instead of an array. This should solve your problem Also I don't know your case but it looks to me that your useQuery should use queryKey: ["similarProducts", selectedIds], as it only depends on selectedIds

Did you find this page helpful?