Skip to content

fix(package/gqty): useTransactionQuery should work without suspense #2188

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/wise-dingos-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gqty/react': patch
---

useTransactionQuery should work without suspense
56 changes: 56 additions & 0 deletions examples/gnt/app/useTransactionQuery/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'use client';

import { useState } from 'react';
import { useTransactionQuery } from '~/gqty/react';

export default function UseTransactionQuery() {
const [skip, setSkip] = useState(false);
const { data, isLoading, error } = useTransactionQuery(
(query) => {
return query
.characters({
filter: {
name: 'Rick',
},
})
?.results?.map((character) => ({
id: character?.id,
name: character?.name,
}));
},
{ skip }
);

return (
<main className="p-5 min-h-screen">
<h1 className="text-2xl font-semibold">Use Transaction Query</h1>

<input
id="boolSkip"
type="checkbox"
checked={skip}
onChange={() => setSkip(!skip)}
/>

<label className="ml-2" htmlFor="boolSkip">
Skip
</label>

{error && <div>Error: {error.message}</div>}

{!data?.[0]?.id && isLoading && <div>Loading ...</div>}

{data?.[0]?.id && (
<ol
className={`list-decimal list-inside ${
isLoading ? 'opacity-50' : ''
}`}
>
{data.map((character) => (
<li key={character?.id ?? 0}>{character?.name}</li>
))}
</ol>
)}
</main>
);
}
9 changes: 5 additions & 4 deletions packages/react/package.json
Original file line number Diff line number Diff line change
@@ -102,8 +102,8 @@
"@types/node": "^22.13.4",
"@types/react": "^18.3.18",
"@types/use-sync-external-store": "^0.0.6",
"@typescript-eslint/eslint-plugin": "^8.24.1",
"@typescript-eslint/parser": "^8.24.1",
"@typescript-eslint/eslint-plugin": "^8.26.0",
"@typescript-eslint/parser": "^8.26.0",
"eslint": "^9.20.1",
"eslint-plugin-you-dont-need-lodash-underscore": "^6.14.0",
"gqty": "workspace:^",
@@ -115,10 +115,11 @@
"lodash-es": "^4.17.21",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-error-boundary": "^5.0.0",
"react-test-renderer": "^18.3.1",
"test-utils": "workspace:^",
"type-fest": "^4.35.0",
"typescript-eslint": "^8.24.1"
"type-fest": "^4.37.0",
"typescript-eslint": "^8.26.0"
},
"peerDependencies": {
"gqty": "workspace:^3.4.1",
7 changes: 7 additions & 0 deletions packages/react/src/query/useTransactionQuery.ts
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ import {
type GQtyError,
type RetryOptions,
} from 'gqty';
import { useEffect } from 'react';
import {
translateFetchPolicy,
type LegacyFetchPolicy,
@@ -106,6 +107,12 @@ export function createUseTransactionQuery<TSchema extends BaseGeneratedSchema>(
}
}, [query.$state.error]);

useEffect(() => {
if (!skip) {
query.$refetch(false);
}
}, [skip]);

return skip
? {
isCalled: false,
134 changes: 134 additions & 0 deletions packages/react/test/useTransactionQuery.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { render, renderHook, waitFor } from '@testing-library/react';
import { GQtyError } from 'gqty';
import React, { act, Suspense } from 'react';
import ReactDOM from 'react-dom/client';
import { ErrorBoundary } from 'react-error-boundary';
import { createReactTestClient } from './utils';

describe('useTransactionQuery', () => {
it('should fetch without suspense', async () => {
const { useTransactionQuery } = await createReactTestClient();

const { result } = renderHook(() =>
useTransactionQuery((query) => query.hello, { suspense: false })
);

expect(result.current.data).toBeUndefined();
await waitFor(() => expect(result.current.data).toBe('hello world'));
});

it('should fetch with suspense', async () => {
const { useTransactionQuery } = await createReactTestClient();

const MyComponent = () => {
const { data, error } = useTransactionQuery((query) => query.hello, {
suspense: true,
});

return (
<>
<div data-testid="error">{error?.message}</div>
<div data-testid="data">{data}</div>
</>
);
};

const screen = render(
<Suspense fallback="Loading...">
<MyComponent />
</Suspense>
);

await waitFor(() => expect(screen.getByText('Loading...')).toBeDefined());
await waitFor(() => expect(screen.getByText('hello world')).toBeDefined());

expect(screen.getByTestId('error').textContent).toBe('');
});

it('should handle errors without suspense', async () => {
const { useTransactionQuery } = await createReactTestClient(
undefined,
async () => {
throw new GQtyError('Network error');
}
);
const onError = jest.fn();

const { result } = renderHook(() =>
useTransactionQuery((query) => query.hello, { suspense: false, onError })
);

await waitFor(() => {
// expect(result.current.error).toBeDefined();
expect(result.current.error?.message).toBe('Network error');
});
expect(onError).toHaveBeenCalled();
});

it.skip('should handle errors with suspense', async () => {
const { useTransactionQuery } = await createReactTestClient(
undefined,
async () => {
console.log('fetcher called');
throw new GQtyError('Network error');
}
);
const onError = jest.fn();

const MyComponent = () => {
const { data, error } = useTransactionQuery((query) => query.hello, {
suspense: true,
onError,
});

return (
<>
<div data-testid="error">{error?.message}</div>
<div data-testid="data">{data}</div>
</>
);
};

let container: HTMLDivElement | null = null;
try {
container = document.createElement('div');
document.body.appendChild(container);

act(() => {
ReactDOM.createRoot(container!).render(
<ErrorBoundary fallbackRender={({ error }) => error.message}>
<Suspense fallback="Loading...">
<MyComponent />
</Suspense>
</ErrorBoundary>
);
});

await waitFor(() => expect(container?.innerText).toBe('Network error'));
// expect(screen.getByTestId('data').textContent).toBe('');
expect(onError).toHaveBeenCalled();
} finally {
if (container) {
document.body.removeChild(container);
}
}
});

it('should skip fetching when skip is true', async () => {
const mockFetch = jest.fn();
const { useTransactionQuery } = await createReactTestClient(
undefined,
async (payload) => {
mockFetch(payload);
return {};
}
);

renderHook(() =>
useTransactionQuery((query) => query.hello, { skip: true })
);

await new Promise((r) => setTimeout(r, 100));
expect(mockFetch).not.toHaveBeenCalled();
});
});
133 changes: 75 additions & 58 deletions pnpm-lock.yaml