react-apollo-hooks icon indicating copy to clipboard operation
react-apollo-hooks copied to clipboard

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

Open MarioKrstevski opened this issue 6 years ago • 1 comments

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?

MarioKrstevski avatar Jul 22 '19 18:07 MarioKrstevski

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.

dominictobias avatar Oct 28 '19 13:10 dominictobias