Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
at main 1.8 kB view raw
1'use client'; 2 3import * as React from 'react'; 4import { useDataHydrationContext } from './DataHydrationContext'; 5import { SSRContext } from './Provider'; 6 7export const symbolString = 'urql_transport'; 8export const urqlTransportSymbol = Symbol.for(symbolString); 9 10export type UrqlResult = { data?: any; error?: any; extensions?: any }; 11 12export function useUrqlValue(operationKey: number): void { 13 const ssrExchange = React.useContext(SSRContext); 14 const rehydrationContext = useDataHydrationContext(); 15 16 if (!ssrExchange) { 17 throw new Error( 18 'Missing "UrqlProvider" component as a parent or did not pass in an "ssrExchange" to the Provider.' 19 ); 20 } 21 22 if (typeof window == 'undefined') { 23 const data = ssrExchange.extractData(); 24 if (rehydrationContext && data[operationKey]) { 25 const res = data[operationKey]; 26 const parsed = { 27 ...res, 28 extensions: res.extensions 29 ? JSON.parse(res.extensions) 30 : res.extensions, 31 data: res.data ? JSON.parse(res.data) : res.data, 32 error: res.error, 33 }; 34 rehydrationContext.operationValuesByKey[operationKey] = parsed; 35 } 36 } else { 37 const stores = (window[urqlTransportSymbol as any] || 38 []) as unknown as Array<{ 39 rehydrate: Record<number, UrqlResult>; 40 }>; 41 42 const store = stores.find( 43 x => x && x.rehydrate && x.rehydrate[operationKey] 44 ); 45 if (store) { 46 const result = store.rehydrate && store.rehydrate[operationKey]; 47 if (result) { 48 delete store.rehydrate[operationKey]; 49 ssrExchange.restoreData({ 50 [operationKey]: { 51 extensions: JSON.stringify(result.extensions), 52 data: JSON.stringify(result.data), 53 error: result.error, 54 }, 55 }); 56 delete store.rehydrate[operationKey]; 57 } 58 } 59 } 60}