Error: Rendered more hooks than during the previous render.

https://i.imgur.com/9FCsFhb.png Hey, im a noob currently and I get sometimes this error, but I dont know why. I googled and found some explanations but I dont get it tbh. Someone can explain me why this error occurs. ❤️
Imgur
Solution:
You can't conditionally call hooks in that manner. If you want to call that useQuery hook only when you have a user, then you have to do something like this: ``` const { data: sessionData } = useSession(); ...
Jump to solution
5 Replies
Josh
Josh9mo ago
Any sort of "use" should only every be used on the top level of the component. Since it's inside the if statement you are conditionally rendering a hook, which is illegal This is explained in more detail on the react docs, which if you're learning react, that should be the first thing you read they explain why this is illegal and how to get around it there
Solution
jeff.kershner
jeff.kershner9mo ago
You can't conditionally call hooks in that manner. If you want to call that useQuery hook only when you have a user, then you have to do something like this:
const { data: sessionData } = useSession();

const data = api.example.getUserGuilds.useQuery({
userId: sessionData.user.id,
}, sessionData?.user !== null);
const { data: sessionData } = useSession();

const data = api.example.getUserGuilds.useQuery({
userId: sessionData.user.id,
}, sessionData?.user !== null);
The first parameter to useQuery is the object with your parameters, and the second parameter is the condition on when to call it. If sessionData?.user !== null (probably could be shortened to sessionData?.user), then call your userQuery. Make sense?
papsn
papsn9mo ago
Makes Sense, but i get an Error that Sessiondata is a String and Not String || undefined
jeff.kershner
jeff.kershner9mo ago
Try: sessionData?.user !== undefined Or: sessionData?.user !== “”
papsn
papsn9mo ago
got it, made them to components and used cond. rendering thx!