Reputation: 69
Im using Typescript, React- and graphql with the urql client library.
My Query looks something like this:
query objectId($id: Int!) {
object(id: $id) {
id
name
__typename
}
}
This is how I call the query:
const [{ data }] = useObjectIdQuery({ variables: { id }, pause: !id });
Question:
How can i refetch every n seconds without reloading the page?
My backend reads JSON files and they update consistently. Now I have looked into the documentation here, and also on a bunch of Stackoverflow and no-name sites.
Thank you.
Upvotes: 1
Views: 2558
Reputation: 69
I found out that the documentation provides a function for that. I built myself a hook to use it in the whole project for any query. Just becareful with the query parameter, it has to be the already build graphql DocumentNode
as parameter.
You can import them like this for each Query:
import { ObjecIdDocument } from "../../graphql";
The graphql path may be different in your case.
This is the full Hook
:
import { useEffect } from "react";
import { useQuery } from "urql";
import { DocumentNode } from "graphql";
const useRefreshingQuery = (variables: object, query: DocumentNode, delayInSec: number, pause: boolean) => {
const [result, reexecuteQuery] = useQuery({
query: query,
variables: variables,
pause: pause,
});
useEffect(() => {
if (result.fetching) {
return;
}
const timerId = setTimeout(() => {
reexecuteQuery({ requestPolicy: "network-only" });
}, delayInSec * 1000);
return () => clearTimeout(timerId);
}, [result.fetching, reexecuteQuery, variables]);
return result;
};
export default useRefreshingQuery;
You can use the Hook
like this:
import { ObjecIdDocument } from "../../graphql";
const result = useRefreshingQuery({ id: UID }, ObjectIdDocument, 10, !UID);
Upvotes: 2