TanStackT
TanStack2y ago
5 replies
ordinary-sapphire

Only query when value is not null?

I have a function that returns a useQuery object:

const getSubmissions = (currentProject) => {
    const endpoint = endpoints.api.submissions.index.replace(':id', currentProject);

    return useQuery({
        queryKey: ['submissions'],
        queryFn: () => fetch(endpoint).then((res) => res.json()),
        staleTime: 10 * 1000
    });
};


which is being used in the following functional component (Next.js):

function SubmissionsTable() {
    const { currentProject } = useContext(ProjectContext);

    // Problem: this triggers the request even when currentProject is null
    const { isLoading, isSuccess, error, data, refetch } = getSubmissions(currentProject);

    useEffect(() => {
        if (isLoading) return;

        if (!isSuccess) {
            toast({
                variant: 'destructive',
                title: "Couldn't fetch submissions",
                description: 'Try again later or contact support'
            });
            return;
        }

        setSubmissions(validate.data);
    }, [isSuccess, data]);

    if (isLoading) return <LoadingCard />;

    return <DataTable columns={columns} data={submissions} />;
}


However, getSubmissions(currentProject) triggers the request even when currentProject is null.

How do I solve this? I can't just wrap an if-statement around it as the useEffect is dependend on isSuccess &
data
.

I tried adding if (!currentProject) return <LoadingCard />; above it but this causes rendering issues.
Was this page helpful?