Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explination needed with useQuery causes infinite loop when variables passed (I found my bug) #198

Open
MarioKrstevski opened this issue Jul 22, 2019 · 1 comment

Comments

@MarioKrstevski
Copy link

Can anyone explain how this works, I found my error but I don't really understand how it all works, I wanted to pass the current date to the useQuery as a variable.

Bad version that was causing for the query to ininitely loop

const {data, loading, error} = useQuery(GET_DAILY_MENU, { 
    variables : {restaurant: dataR.getRestaurants, date: new Date().toString()}
});

Fixed: Without new keyword

const {data, loading, error} = useQuery(GET_DAILY_MENU, { 
    variables : {restaurant: dataR.getRestaurants, date: Date().toString()}
});

Can someone explain in simple terms (or complex if you can't otherwise) why this happens?

@dominictobias
Copy link

I just encountered this too. Seems like variables are evaluated every render which is unexpected since this is a hook without a dependency array. So each render your date slightly changes and another request is made.

I solved this by getting the current time once when the component is created:

const now = useRef(new Date());

and using now.current instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants