vors
vors•3y ago

Ok so more stupid problems from me 😅

Ok so more stupid problems from me 😅 I want to have two for-loops in a sense: one loops over the entity I call "generation" and the second one loops over "images" inside the "generation". I'm trying to do both things with useQuery , in the second case I'm using results of the first one.... and react doesn't like that! I'm getting Rendered more hooks than during the previous render The code is roughly speaking
const generations = useQuery("listGenerations", "foo") || [];
...

{generations.map(generation => {
const imageUrls = useQuery("getImagesForGeneration", generation) || [];

const imageDom = imageUrls.map(imageUrl => {
return (<li key={generation._id.toString()}>
<span>
<img
src={`/api/get-image/${imageUrl}`}
height="300px"
width="auto"
/>
</span>
</li>)
})

return (
<li key={generation._id.toString()}>
<span>{g}</span>
{imageDom}
</li>
)
})}
const generations = useQuery("listGenerations", "foo") || [];
...

{generations.map(generation => {
const imageUrls = useQuery("getImagesForGeneration", generation) || [];

const imageDom = imageUrls.map(imageUrl => {
return (<li key={generation._id.toString()}>
<span>
<img
src={`/api/get-image/${imageUrl}`}
height="300px"
width="auto"
/>
</span>
</li>)
})

return (
<li key={generation._id.toString()}>
<span>{g}</span>
{imageDom}
</li>
)
})}
8 Replies
vors
vorsOP•3y ago
Do I need to create a new query where I mish-mash both of these things together and listen on it instead?
ari
ari•3y ago
Ah! React can't render hooks conditionally (or change the number of hooks rendered). One way to get this working is to refactor the mapper function into its own component i.e.
generations.map(generation => <GenerationListItem <props here> />)
generations.map(generation => <GenerationListItem <props here> />)
That way, each list item is one component that always calls exactly one useQuery hook
vors
vorsOP•3y ago
hm sorry I don't fully follow -- where is the second (inner) query will happen? Is it inside the GenerationListItem based on props?
ari
ari•3y ago
Yup! The getImagesForGeneration call would be inside GenerationListItem
vors
vorsOP•3y ago
Awesome, let me try that. And thank you so much for the quick replay!
ari
ari•3y ago
No worries, I just so happened to be online on discord, gaming 😄 Let me know how it goes!
vors
vorsOP•3y ago
awesome, works like a charm!
ari
ari•3y ago
yay!

Did you find this page helpful?