Skip to content

Commit

Permalink
resolve promise
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock committed Apr 23, 2024
1 parent 4aa9096 commit 17f8336
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 3 deletions.
4 changes: 3 additions & 1 deletion examples/with-defer-stream-directives/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ const client = new Client({
function App() {
return (
<Provider value={client}>
<Songs />
<React.Suspense fallback={<p>Loading...</p>}>
<Songs />
</React.Suspense>
</Provider>
);
}
Expand Down
6 changes: 6 additions & 0 deletions examples/with-defer-stream-directives/src/Songs.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ const SONGS_QUERY = gql`
firstVerse
...secondVerseFields @defer
}
alphabet @stream(initialCount: 3) {
char
}
}
${SecondVerseFragment}
Expand Down Expand Up @@ -50,6 +53,9 @@ const LocationsList = () => {
{data && (
<>
<Song song={data.song} />
{data.alphabet.map(i => (
<div key={i.char}>{i.char}</div>
))}
</>
)}
</div>
Expand Down
10 changes: 9 additions & 1 deletion packages/react-urql/src/hooks/cache.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { pipe, subscribe } from 'wonka';
import type { Client, OperationResult } from '@urql/core';

type CacheEntry = OperationResult | Promise<unknown> | undefined;
export type FragmentPromise = Promise<unknown> & {
_resolve: () => void;
_resolved: boolean;
};
type CacheEntry =
| OperationResult
| Promise<unknown>
| FragmentPromise
| undefined;

interface Cache {
get(key: number): CacheEntry;
Expand Down
17 changes: 16 additions & 1 deletion packages/react-urql/src/hooks/useFragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type {

import { useClient } from '../context';
import { useRequest } from './useRequest';
import type { FragmentPromise } from './cache';
import { getCacheForClient } from './cache';

import { hasDepsChanged } from './state';
Expand Down Expand Up @@ -172,7 +173,12 @@ export function useFragment<Data>(
cache.set(request.key, newResult.data as any);
return { data: newResult.data as any, fetching: false };
} else if (suspense) {
const promise = new Promise(() => {});
let _resolve;
const promise = new Promise(res => {
_resolve = res;
}) as FragmentPromise;
promise._resolve = _resolve;
promise._resolved = false;
cache.set(request.key, promise);
throw promise;
} else {
Expand All @@ -182,6 +188,15 @@ export function useFragment<Data>(
throw cached;
}

if (
'_resolve' in cached &&
'_resolved' in cached &&
!cached._resolved &&
typeof cached._resolve == 'function'
) {
cached._resolve();
cached._resolved = true;
}
return { fetching: false, data: (cached as OperationResult).data };
},
[cache, request]
Expand Down

0 comments on commit 17f8336

Please sign in to comment.