react-apollo-hooks
react-apollo-hooks copied to clipboard
Explination needed with useQuery causes infinite loop when variables passed (I found my bug)
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?
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.