next-sanity 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/currentUser.d.ts +1 -1
- package/dist/next-sanity.cjs.development.js +19 -7
- package/dist/next-sanity.cjs.development.js.map +1 -1
- package/dist/next-sanity.cjs.production.min.js +1 -1
- package/dist/next-sanity.cjs.production.min.js.map +1 -1
- package/dist/next-sanity.esm.js +19 -7
- package/dist/next-sanity.esm.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/useSubscription.d.ts +1 -1
- package/package.json +12 -12
- package/src/currentUser.ts +8 -1
- package/src/types.ts +7 -0
- package/src/useSubscription.ts +10 -3
package/README.md
CHANGED
|
@@ -77,6 +77,13 @@ export const config = {
|
|
|
77
77
|
* Authenticated request (like preview) will always bypass the CDN
|
|
78
78
|
**/
|
|
79
79
|
useCdn: process.env.NODE_ENV === 'production',
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* OPTIONAL config to enable authentication with custom token
|
|
83
|
+
* You might need this if you host the preview on a different url than Sanity Studio
|
|
84
|
+
*/
|
|
85
|
+
token: '<sanity access token>',
|
|
86
|
+
EventSource: /* provide your own event source implementation. Required in browsers to support the above token parameter. */
|
|
80
87
|
}
|
|
81
88
|
```
|
|
82
89
|
|
package/dist/currentUser.d.ts
CHANGED
|
@@ -8,4 +8,4 @@ export declare function createCurrentUserHook({ projectId }: {
|
|
|
8
8
|
error: Error | undefined;
|
|
9
9
|
loading: boolean;
|
|
10
10
|
};
|
|
11
|
-
export declare function getCurrentUser(projectId: string, abort: Aborter): Promise<CurrentUser | null>;
|
|
11
|
+
export declare function getCurrentUser(projectId: string, abort: Aborter, token?: string): Promise<CurrentUser | null>;
|
|
@@ -79,14 +79,19 @@ function getAborter() {
|
|
|
79
79
|
|
|
80
80
|
function createCurrentUserHook(_ref) {
|
|
81
81
|
var projectId = _ref.projectId;
|
|
82
|
+
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
82
83
|
return function () {
|
|
83
84
|
return useCurrentUser(projectId);
|
|
84
85
|
};
|
|
85
86
|
}
|
|
86
|
-
function getCurrentUser(projectId, abort) {
|
|
87
|
+
function getCurrentUser(projectId, abort, token) {
|
|
88
|
+
var headers = token ? {
|
|
89
|
+
Authorization: "Bearer " + token
|
|
90
|
+
} : undefined;
|
|
87
91
|
return fetch("https://" + projectId + ".api.sanity.io/v1/users/me", {
|
|
88
92
|
credentials: 'include',
|
|
89
|
-
signal: abort.signal
|
|
93
|
+
signal: abort.signal,
|
|
94
|
+
headers: headers
|
|
90
95
|
}).then(function (res) {
|
|
91
96
|
return res.json();
|
|
92
97
|
}).then(function (res) {
|
|
@@ -119,10 +124,13 @@ function useCurrentUser(projectId) {
|
|
|
119
124
|
};
|
|
120
125
|
}
|
|
121
126
|
|
|
122
|
-
var EMPTY_PARAMS = {};
|
|
127
|
+
var EMPTY_PARAMS = {}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
128
|
+
|
|
123
129
|
function createPreviewSubscriptionHook(_ref) {
|
|
124
130
|
var projectId = _ref.projectId,
|
|
125
131
|
dataset = _ref.dataset,
|
|
132
|
+
token = _ref.token,
|
|
133
|
+
EventSource = _ref.EventSource,
|
|
126
134
|
_ref$documentLimit = _ref.documentLimit,
|
|
127
135
|
documentLimit = _ref$documentLimit === void 0 ? 3000 : _ref$documentLimit;
|
|
128
136
|
// Only construct/setup the store when `getStore()` is called
|
|
@@ -143,7 +151,8 @@ function createPreviewSubscriptionHook(_ref) {
|
|
|
143
151
|
query: query,
|
|
144
152
|
params: params,
|
|
145
153
|
initialData: initialData,
|
|
146
|
-
enabled: enabled ? typeof window !== 'undefined' : false
|
|
154
|
+
enabled: enabled ? typeof window !== 'undefined' : false,
|
|
155
|
+
token: token
|
|
147
156
|
});
|
|
148
157
|
};
|
|
149
158
|
|
|
@@ -164,6 +173,8 @@ function createPreviewSubscriptionHook(_ref) {
|
|
|
164
173
|
projectId: projectId,
|
|
165
174
|
dataset: dataset,
|
|
166
175
|
documentLimit: documentLimit,
|
|
176
|
+
token: token,
|
|
177
|
+
EventSource: EventSource,
|
|
167
178
|
listen: true,
|
|
168
179
|
overlayDrafts: true,
|
|
169
180
|
subscriptionThrottleMs: 10
|
|
@@ -181,7 +192,8 @@ function useQuerySubscription(options) {
|
|
|
181
192
|
query = options.query,
|
|
182
193
|
initialData = options.initialData,
|
|
183
194
|
_options$enabled = options.enabled,
|
|
184
|
-
enabled = _options$enabled === void 0 ? false : _options$enabled
|
|
195
|
+
enabled = _options$enabled === void 0 ? false : _options$enabled,
|
|
196
|
+
token = options.token;
|
|
185
197
|
|
|
186
198
|
var _useState = react.useState(),
|
|
187
199
|
error = _useState[0],
|
|
@@ -206,7 +218,7 @@ function useQuerySubscription(options) {
|
|
|
206
218
|
setLoading(true);
|
|
207
219
|
var aborter = getAborter();
|
|
208
220
|
var subscription;
|
|
209
|
-
getCurrentUser(projectId, aborter).then(function (user) {
|
|
221
|
+
getCurrentUser(projectId, aborter, token).then(function (user) {
|
|
210
222
|
if (user) {
|
|
211
223
|
return;
|
|
212
224
|
} // eslint-disable-next-line no-console
|
|
@@ -237,7 +249,7 @@ function useQuerySubscription(options) {
|
|
|
237
249
|
|
|
238
250
|
aborter.abort();
|
|
239
251
|
};
|
|
240
|
-
}, [getStore, query, params, enabled]);
|
|
252
|
+
}, [getStore, query, params, enabled, projectId, token]);
|
|
241
253
|
return {
|
|
242
254
|
data: typeof data === 'undefined' ? initialData : data,
|
|
243
255
|
loading: loading,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next-sanity.cjs.development.js","sources":["../src/client.ts","../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts"],"sourcesContent":["import sanityClient from '@sanity/client'\nimport type {ClientConfig, SanityClient} from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n","export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(projectId: string, abort: Aborter): Promise<CurrentUser | null> {\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {useState, useEffect, useMemo} from 'react'\nimport {GroqStore, Subscription} from '@sanity/groq-store'\nimport {ProjectConfig} from './types'\nimport {getCurrentUser} from './currentUser'\nimport {getAborter, Aborter} from './aborter'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n}) {\n const {getStore, projectId, query, initialData, enabled = false} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n"],"names":["createClient","config","sanityClient","MockAbortController","aborted","abort","_signal","getAborter","AbortController","createCurrentUserHook","projectId","useCurrentUser","getCurrentUser","fetch","credentials","signal","then","res","json","id","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","EMPTY_PARAMS","createPreviewSubscriptionHook","dataset","documentLimit","store","usePreviewSubscription","query","options","params","initialData","enabled","useQuerySubscription","getStore","window","groqStore","Error","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs","setLoading","setData","useParams","subscription","user","console","warn","subscribe","result","finally","unsubscribe","stringifiedParams","useMemo","JSON","stringify","parse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAGgBA,aAAaC;AAC3B,SAAOC,YAAY,CAACD,MAAD,CAAnB;AACD;;;;;;;;;;;;;;;;;;;;;ICAKE;AAAN;AACE,gBAAA,GAAU;AAACC,MAAAA,OAAO,EAAE;AAAV,KAAV;AAOD;;;;SAHCC,QAAA;AACE,SAAKC,OAAL,CAAaF,OAAb,GAAuB,IAAvB;AACD;;;;SALD;AACE,aAAO,KAAKE,OAAZ;AACD;;;;;;AAMH,SAAgBC;AACd,SAAO,OAAOC,eAAP,KAA2B,WAA3B,GACH,IAAIL,mBAAJ,EADG,GAEH,IAAIK,eAAJ,EAFJ;AAGD;;SCfeC;MAAuBC,iBAAAA;AACrC,SAAO;AAAA,WAAMC,cAAc,CAACD,SAAD,CAApB;AAAA,GAAP;AACD;AAED,SAAgBE,eAAeF,WAAmBL;AAChD,SAAOQ,KAAK,cAAYH,SAAZ,iCAAmD;AAC7DI,IAAAA,WAAW,EAAE,SADgD;AAE7DC,IAAAA,MAAM,EAAEV,KAAK,CAACU;AAF+C,GAAnD,CAAL,CAIJC,IAJI,CAIC,UAACC,GAAD;AAAA,WAASA,GAAG,CAACC,IAAJ,EAAT;AAAA,GAJD,EAKJF,IALI,CAKC,UAACC,GAAD;AAAA,WAAUA,GAAG,QAA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,CAAhB;AAAA,KArBX;;AAwBA,WAAO;AACL,UAAIG,YAAJ,EAAkB;AAChBA,QAAAA,YAAY,CAACO,WAAb;AACD;;AAEDpC,MAAAA,OAAO,CAACrB,KAAR;AACD,KAND;AAOD,GAxCQ,EAwCN,CAACsC,QAAD,EAAWN,KAAX,EAAkBE,MAAlB,EAA0BE,OAA1B,CAxCM,CAAT;AA0CA,SAAO;AACLpB,IAAAA,IAAI,EAAE,OAAOA,IAAP,KAAgB,WAAhB,GAA8BmB,WAA9B,GAA4CnB,IAD7C;AAELS,IAAAA,OAAO,EAAPA,OAFK;AAGLP,IAAAA,KAAK,EAALA;AAHK,GAAP;AAKD;;;AAGD,SAAS+B,SAAT,CAAmBf,MAAnB;AACE,MAAMwB,iBAAiB,GAAGC,aAAO,CAAC;AAAA,WAAMC,IAAI,CAACC,SAAL,CAAe3B,MAAf,CAAN;AAAA,GAAD,EAA+B,CAACA,MAAD,CAA/B,CAAjC;AACA,SAAOyB,aAAO,CAAC;AAAA,WAAMC,IAAI,CAACE,KAAL,CAAWJ,iBAAX,CAAN;AAAA,GAAD,EAAsC,CAACA,iBAAD,CAAtC,CAAd;AACD;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"next-sanity.cjs.development.js","sources":["../src/client.ts","../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts"],"sourcesContent":["import sanityClient from '@sanity/client'\nimport type {ClientConfig, SanityClient} from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n","export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(\n projectId: string,\n abort: Aborter,\n token?: string\n): Promise<CurrentUser | null> {\n const headers = token ? {Authorization: `Bearer ${token}`} : undefined\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n headers,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {useState, useEffect, useMemo} from 'react'\nimport {GroqStore, Subscription} from '@sanity/groq-store'\nimport {ProjectConfig} from './types'\nimport {getCurrentUser} from './currentUser'\nimport {getAborter, Aborter} from './aborter'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n token,\n EventSource,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n token,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n token,\n EventSource,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n token?: string\n}) {\n const {getStore, projectId, query, initialData, enabled = false, token} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter, token)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled, projectId, token])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n"],"names":["createClient","config","sanityClient","MockAbortController","aborted","abort","_signal","getAborter","AbortController","createCurrentUserHook","projectId","useCurrentUser","getCurrentUser","token","headers","Authorization","undefined","fetch","credentials","signal","then","res","json","id","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","EMPTY_PARAMS","createPreviewSubscriptionHook","dataset","EventSource","documentLimit","store","usePreviewSubscription","query","options","params","initialData","enabled","useQuerySubscription","getStore","window","groqStore","Error","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs","setLoading","setData","useParams","subscription","user","console","warn","subscribe","result","finally","unsubscribe","stringifiedParams","useMemo","JSON","stringify","parse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAGgBA,aAAaC;EAC3B,OAAOC,YAAY,CAACD,MAAD,CAAnB;AACD;;;;;;;;;;;;;;;;;;;;;ICAKE;EAAN;IACE,YAAA,GAAU;MAACC,OAAO,EAAE;KAApB;;;;;SAIAC,QAAA;IACE,KAAKC,OAAL,CAAaF,OAAb,GAAuB,IAAvB;;;;;SAJF;MACE,OAAO,KAAKE,OAAZ;;;;;;;AAOJ,SAAgBC;EACd,OAAO,OAAOC,eAAP,KAA2B,WAA3B,GACH,IAAIL,mBAAJ,EADG,GAEH,IAAIK,eAAJ,EAFJ;AAGD;;SCfeC;MAAuBC,iBAAAA;;EAErC,OAAO;IAAA,OAAMC,cAAc,CAACD,SAAD,CAApB;GAAP;AACD;AAED,SAAgBE,eACdF,WACAL,OACAQ;EAEA,IAAMC,OAAO,GAAGD,KAAK,GAAG;IAACE,aAAa,cAAYF;GAA7B,GAAwCG,SAA7D;EACA,OAAOC,KAAK,cAAYP,SAAZ,iCAAmD;IAC7DQ,WAAW,EAAE,SADgD;IAE7DC,MAAM,EAAEd,KAAK,CAACc,MAF+C;IAG7DL,OAAO,EAAPA;GAHU,CAAL,CAKJM,IALI,CAKC,UAACC,GAAD;IAAA,OAASA,GAAG,CAACC,IAAJ,EAAT;GALD,EAMJF,IANI,CAMC,UAACC,GAAD;IAAA,OAAUA,GAAG,QAAH,IAAAA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OAAOA,IAAP,KAAgB,WAAhB,GAA8BoB,WAA9B,GAA4CpB,IAD7C;IAELS,OAAO,EAAPA,OAFK;IAGLP,KAAK,EAALA;GAHF;AAKD;;;AAGD,SAASgC,SAAT,CAAmBf,MAAnB;EACE,IAAMwB,iBAAiB,GAAGC,aAAO,CAAC;IAAA,OAAMC,IAAI,CAACC,SAAL,CAAe3B,MAAf,CAAN;GAAD,EAA+B,CAACA,MAAD,CAA/B,CAAjC;EACA,OAAOyB,aAAO,CAAC;IAAA,OAAMC,IAAI,CAACE,KAAL,CAAWJ,iBAAX,CAAN;GAAD,EAAsC,CAACA,iBAAD,CAAtC,CAAd;AACD;;;;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("@sanity/client")),r=require("react"),n=e(require("groq")),o=function(){function e(){this._signal={aborted:!1}}var t,r;return e.prototype.abort=function(){this._signal.aborted=!0},t=e,(r=[{key:"signal",get:function(){return this._signal}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function i(){return"undefined"==typeof AbortController?new o:new AbortController}function u(e,t){return fetch("https://"+e+".api.sanity.io/v1/users/me",{credentials:"include",signal:t.signal}).then((function(e){return e.json()})).then((function(e){return null!=e&&e.id?e:null}))}var a={};exports.groq=n,exports.createClient=function(e){return t(e)},exports.createCurrentUserHook=function(e){var t=e.projectId;return function(){return function(e){var t=r.useState(),n=t[0],o=t[1],a=r.useState(),c=a[0],f=a[1];return r.useEffect((function(){var t=i();return u(e,t).then(o).catch((function(e){return"AbortError"!==e.name&&f(e)})),function(){t.abort()}}),[e]),{data:n,error:c,loading:null!==n||!c}}(t)}},exports.createPreviewSubscriptionHook=function(e){var t,n=e.projectId,o=e.dataset,c=e.
|
|
1
|
+
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("@sanity/client")),r=require("react"),n=e(require("groq")),o=function(){function e(){this._signal={aborted:!1}}var t,r;return e.prototype.abort=function(){this._signal.aborted=!0},t=e,(r=[{key:"signal",get:function(){return this._signal}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function i(){return"undefined"==typeof AbortController?new o:new AbortController}function u(e,t,r){return fetch("https://"+e+".api.sanity.io/v1/users/me",{credentials:"include",signal:t.signal,headers:r?{Authorization:"Bearer "+r}:void 0}).then((function(e){return e.json()})).then((function(e){return null!=e&&e.id?e:null}))}var a={};exports.groq=n,exports.createClient=function(e){return t(e)},exports.createCurrentUserHook=function(e){var t=e.projectId;return function(){return function(e){var t=r.useState(),n=t[0],o=t[1],a=r.useState(),c=a[0],f=a[1];return r.useEffect((function(){var t=i();return u(e,t).then(o).catch((function(e){return"AbortError"!==e.name&&f(e)})),function(){t.abort()}}),[e]),{data:n,error:c,loading:null!==n||!c}}(t)}},exports.createPreviewSubscriptionHook=function(e){var t,n=e.projectId,o=e.dataset,c=e.token,f=e.EventSource,s=e.documentLimit,l=void 0===s?3e3:s;return function(e,t){void 0===t&&(t={});var o=t.params;return function(e){var t=e.getStore,n=e.projectId,o=e.query,a=e.initialData,c=e.enabled,f=void 0!==c&&c,s=e.token,l=r.useState(),d=l[0],b=l[1],p=r.useState(!1),v=p[0],g=p[1],h=r.useState(),y=h[0],m=h[1],w=function(e){var t=r.useMemo((function(){return JSON.stringify(e)}),[e]);return r.useMemo((function(){return JSON.parse(t)}),[t])}(e.params);return r.useEffect((function(){if(f){g(!0);var e,r=i();return u(n,r,s).then((function(e){if(!e)throw console.warn("Not authenticated - preview not available"),new Error("Not authenticated - preview not available")})).then((function(){return t(r)})).then((function(t){e=t.subscribe(o,w,(function(e,t){e?b(e):m(t)}))})).catch((function(e){return"AbortError"===e.name?null:b(e)})).finally((function(){return g(!1)})),function(){e&&e.unsubscribe(),r.abort()}}}),[t,o,w,f,n,s]),{data:void 0===y?a:y,loading:v,error:d}}({getStore:d,projectId:n,query:e,params:void 0===o?a:o,initialData:t.initialData,enabled:!!t.enabled&&"undefined"!=typeof window,token:c})};function d(e){return t||(t=new Promise((function(e){e(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach((function(r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})})),t.default=e,t}(require("@sanity/groq-store")))})).then((function(t){var r=t.groqStore;if(e.signal.aborted){var i=new Error("Cancelling groq store creation");return i.name="AbortError",Promise.reject(i)}return r({projectId:n,dataset:o,documentLimit:l,token:c,EventSource:f,listen:!0,overlayDrafts:!0,subscriptionThrottleMs:10})}))),t}};
|
|
2
2
|
//# sourceMappingURL=next-sanity.cjs.production.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next-sanity.cjs.production.min.js","sources":["../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts","../src/client.ts"],"sourcesContent":["export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(projectId: string
|
|
1
|
+
{"version":3,"file":"next-sanity.cjs.production.min.js","sources":["../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts","../src/client.ts"],"sourcesContent":["export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(\n projectId: string,\n abort: Aborter,\n token?: string\n): Promise<CurrentUser | null> {\n const headers = token ? {Authorization: `Bearer ${token}`} : undefined\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n headers,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {useState, useEffect, useMemo} from 'react'\nimport {GroqStore, Subscription} from '@sanity/groq-store'\nimport {ProjectConfig} from './types'\nimport {getCurrentUser} from './currentUser'\nimport {getAborter, Aborter} from './aborter'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n token,\n EventSource,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n token,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n token,\n EventSource,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n token?: string\n}) {\n const {getStore, projectId, query, initialData, enabled = false, token} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter, token)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled, projectId, token])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n","import sanityClient from '@sanity/client'\nimport type {ClientConfig, SanityClient} from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n"],"names":["MockAbortController","this","aborted","abort","_signal","getAborter","AbortController","getCurrentUser","projectId","token","fetch","credentials","signal","headers","Authorization","undefined","then","res","json","id","EMPTY_PARAMS","config","sanityClient","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","useCurrentUser","store","dataset","EventSource","documentLimit","query","options","params","getStore","initialData","enabled","setLoading","setData","stringifiedParams","useMemo","JSON","stringify","parse","useParams","subscription","user","console","warn","Error","subscribe","result","finally","unsubscribe","useQuerySubscription","window","groqStore","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs"],"mappings":"qNAKMA,aAAN,aACEC,aAAU,CAACC,SAAS,8BAIpBC,MAAA,WACEF,KAAKG,QAAQF,SAAU,6BAJzB,WACE,OAAOD,KAAKG,yPAOhB,SAAgBC,IACd,MAAkC,oBAApBC,gBACV,IAAIN,EACJ,IAAIM,gBCTV,SAAgBC,EACdC,EACAL,EACAM,GAGA,OAAOC,iBAAiBF,+BAAuC,CAC7DG,YAAa,UACbC,OAAQT,EAAMS,OACdC,QAJcJ,EAAQ,CAACK,wBAAyBL,QAAWM,IAM1DC,MAAK,SAACC,GAAD,OAASA,EAAIC,UAClBF,MAAK,SAACC,GAAD,aAAUA,GAAAA,EAAKE,GAAKF,EAAM,QCfpC,IAAMG,EAAe,gDCHQC,GAC3B,O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LkB,EAAelB,EAAMuB,UAAUnB,EAAOE,GAAQ,SAACV,EAAK4B,GAC9C5B,EACFJ,EAASI,GAETe,EAAQa,SAIb7B,OAAM,SAACC,GAAD,MAA8B,eAAbA,EAAIC,KAAwB,KAAOL,EAASI,MACnE6B,SAAQ,WAAA,OAAMf,GAAW,MAGrB,WACDQ,GACFA,EAAaQ,cAGfhC,EAAQ1B,YAET,CAACuC,EAAUH,EAAOE,EAAQG,EAASpC,EAAWC,IAE1C,CACLe,UAAsB,IAATA,EAAuBmB,EAAcnB,EAClDS,QAAAA,EACAP,MAAAA,GApGOoC,CAAwB,CAC7BpB,SAAAA,EACAlC,UAAAA,EACA+B,MAAAA,EACAE,kBALcrB,IAMduB,YANoDH,EAAxBG,YAO5BC,UAPoDJ,EAAXI,SAOJ,oBAAXmB,OAC1BtD,MAAAA,KAIJ,SAASiC,EAASvC,GAuBhB,OAtBKgC,IACHA,EAAQ,8QAAO,2BAAsBnB,MAAK,gBAAEgD,IAAAA,UAE1C,GAAI7D,EAAMS,OAAOV,QAAS,CACxB,IAAMwB,EAAQ,IAAI+B,MAAM,kCAGxB,OADA/B,EAAMM,KAAO,aACNiC,QAAQC,OAAOxC,GAGxB,OAAOsC,EAAU,CACfxD,UAAAA,EACA4B,QAAAA,EACAE,cAAAA,EACA7B,MAAAA,EACA4B,YAAAA,EACA8B,QAAQ,EACRC,eAAe,EACfC,uBAAwB,SAIvBlC"}
|
package/dist/next-sanity.esm.js
CHANGED
|
@@ -54,14 +54,19 @@ function getAborter() {
|
|
|
54
54
|
|
|
55
55
|
function createCurrentUserHook(_ref) {
|
|
56
56
|
var projectId = _ref.projectId;
|
|
57
|
+
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
57
58
|
return function () {
|
|
58
59
|
return useCurrentUser(projectId);
|
|
59
60
|
};
|
|
60
61
|
}
|
|
61
|
-
function getCurrentUser(projectId, abort) {
|
|
62
|
+
function getCurrentUser(projectId, abort, token) {
|
|
63
|
+
var headers = token ? {
|
|
64
|
+
Authorization: "Bearer " + token
|
|
65
|
+
} : undefined;
|
|
62
66
|
return fetch("https://" + projectId + ".api.sanity.io/v1/users/me", {
|
|
63
67
|
credentials: 'include',
|
|
64
|
-
signal: abort.signal
|
|
68
|
+
signal: abort.signal,
|
|
69
|
+
headers: headers
|
|
65
70
|
}).then(function (res) {
|
|
66
71
|
return res.json();
|
|
67
72
|
}).then(function (res) {
|
|
@@ -94,10 +99,13 @@ function useCurrentUser(projectId) {
|
|
|
94
99
|
};
|
|
95
100
|
}
|
|
96
101
|
|
|
97
|
-
var EMPTY_PARAMS = {};
|
|
102
|
+
var EMPTY_PARAMS = {}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
103
|
+
|
|
98
104
|
function createPreviewSubscriptionHook(_ref) {
|
|
99
105
|
var projectId = _ref.projectId,
|
|
100
106
|
dataset = _ref.dataset,
|
|
107
|
+
token = _ref.token,
|
|
108
|
+
EventSource = _ref.EventSource,
|
|
101
109
|
_ref$documentLimit = _ref.documentLimit,
|
|
102
110
|
documentLimit = _ref$documentLimit === void 0 ? 3000 : _ref$documentLimit;
|
|
103
111
|
// Only construct/setup the store when `getStore()` is called
|
|
@@ -118,7 +126,8 @@ function createPreviewSubscriptionHook(_ref) {
|
|
|
118
126
|
query: query,
|
|
119
127
|
params: params,
|
|
120
128
|
initialData: initialData,
|
|
121
|
-
enabled: enabled ? typeof window !== 'undefined' : false
|
|
129
|
+
enabled: enabled ? typeof window !== 'undefined' : false,
|
|
130
|
+
token: token
|
|
122
131
|
});
|
|
123
132
|
};
|
|
124
133
|
|
|
@@ -139,6 +148,8 @@ function createPreviewSubscriptionHook(_ref) {
|
|
|
139
148
|
projectId: projectId,
|
|
140
149
|
dataset: dataset,
|
|
141
150
|
documentLimit: documentLimit,
|
|
151
|
+
token: token,
|
|
152
|
+
EventSource: EventSource,
|
|
142
153
|
listen: true,
|
|
143
154
|
overlayDrafts: true,
|
|
144
155
|
subscriptionThrottleMs: 10
|
|
@@ -156,7 +167,8 @@ function useQuerySubscription(options) {
|
|
|
156
167
|
query = options.query,
|
|
157
168
|
initialData = options.initialData,
|
|
158
169
|
_options$enabled = options.enabled,
|
|
159
|
-
enabled = _options$enabled === void 0 ? false : _options$enabled
|
|
170
|
+
enabled = _options$enabled === void 0 ? false : _options$enabled,
|
|
171
|
+
token = options.token;
|
|
160
172
|
|
|
161
173
|
var _useState = useState(),
|
|
162
174
|
error = _useState[0],
|
|
@@ -181,7 +193,7 @@ function useQuerySubscription(options) {
|
|
|
181
193
|
setLoading(true);
|
|
182
194
|
var aborter = getAborter();
|
|
183
195
|
var subscription;
|
|
184
|
-
getCurrentUser(projectId, aborter).then(function (user) {
|
|
196
|
+
getCurrentUser(projectId, aborter, token).then(function (user) {
|
|
185
197
|
if (user) {
|
|
186
198
|
return;
|
|
187
199
|
} // eslint-disable-next-line no-console
|
|
@@ -212,7 +224,7 @@ function useQuerySubscription(options) {
|
|
|
212
224
|
|
|
213
225
|
aborter.abort();
|
|
214
226
|
};
|
|
215
|
-
}, [getStore, query, params, enabled]);
|
|
227
|
+
}, [getStore, query, params, enabled, projectId, token]);
|
|
216
228
|
return {
|
|
217
229
|
data: typeof data === 'undefined' ? initialData : data,
|
|
218
230
|
loading: loading,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next-sanity.esm.js","sources":["../src/client.ts","../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts"],"sourcesContent":["import sanityClient from '@sanity/client'\nimport type {ClientConfig, SanityClient} from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n","export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(projectId: string, abort: Aborter): Promise<CurrentUser | null> {\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {useState, useEffect, useMemo} from 'react'\nimport {GroqStore, Subscription} from '@sanity/groq-store'\nimport {ProjectConfig} from './types'\nimport {getCurrentUser} from './currentUser'\nimport {getAborter, Aborter} from './aborter'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n}) {\n const {getStore, projectId, query, initialData, enabled = false} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n"],"names":["createClient","config","sanityClient","MockAbortController","aborted","abort","_signal","getAborter","AbortController","createCurrentUserHook","projectId","useCurrentUser","getCurrentUser","fetch","credentials","signal","then","res","json","id","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","EMPTY_PARAMS","createPreviewSubscriptionHook","dataset","documentLimit","store","usePreviewSubscription","query","options","params","initialData","enabled","useQuerySubscription","getStore","window","groqStore","Error","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs","setLoading","setData","useParams","subscription","user","console","warn","subscribe","result","finally","unsubscribe","stringifiedParams","useMemo","JSON","stringify","parse"],"mappings":";;;;SAGgBA,aAAaC;AAC3B,SAAOC,YAAY,CAACD,MAAD,CAAnB;AACD;;;;;;;;;;;;;;;;;;;;;ICAKE;AAAN;AACE,gBAAA,GAAU;AAACC,MAAAA,OAAO,EAAE;AAAV,KAAV;AAOD;;;;SAHCC,QAAA;AACE,SAAKC,OAAL,CAAaF,OAAb,GAAuB,IAAvB;AACD;;;;SALD;AACE,aAAO,KAAKE,OAAZ;AACD;;;;;;AAMH,SAAgBC;AACd,SAAO,OAAOC,eAAP,KAA2B,WAA3B,GACH,IAAIL,mBAAJ,EADG,GAEH,IAAIK,eAAJ,EAFJ;AAGD;;SCfeC;MAAuBC,iBAAAA;AACrC,SAAO;AAAA,WAAMC,cAAc,CAACD,SAAD,CAApB;AAAA,GAAP;AACD;AAED,SAAgBE,eAAeF,WAAmBL;AAChD,SAAOQ,KAAK,cAAYH,SAAZ,iCAAmD;AAC7DI,IAAAA,WAAW,EAAE,SADgD;AAE7DC,IAAAA,MAAM,EAAEV,KAAK,CAACU;AAF+C,GAAnD,CAAL,CAIJC,IAJI,CAIC,UAACC,GAAD;AAAA,WAASA,GAAG,CAACC,IAAJ,EAAT;AAAA,GAJD,EAKJF,IALI,CAKC,UAACC,GAAD;AAAA,WAAUA,GAAG,QAAH,IAAAA,GAAG,CAAEE,EAAL,GAAUF,GAAV,GAAgB,IAA1B;AAAA,GALD,CAAP;AAMD;;AAED,SAASN,cAAT,CAAwBD,SAAxB;AACE,kBAAwBU,QAAQ,EAAhC;AAAA,MAAOC,IAAP;AAAA,MAAaC,OAAb;;AACA,mBAA0BF,QAAQ,EAAlC;AAAA,MAAOG,KAA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M,CAAT;AA0CA,SAAO;AACLpB,IAAAA,IAAI,EAAE,OAAOA,IAAP,KAAgB,WAAhB,GAA8BmB,WAA9B,GAA4CnB,IAD7C;AAELS,IAAAA,OAAO,EAAPA,OAFK;AAGLP,IAAAA,KAAK,EAALA;AAHK,GAAP;AAKD;;;AAGD,SAAS+B,SAAT,CAAmBf,MAAnB;AACE,MAAMwB,iBAAiB,GAAGC,OAAO,CAAC;AAAA,WAAMC,IAAI,CAACC,SAAL,CAAe3B,MAAf,CAAN;AAAA,GAAD,EAA+B,CAACA,MAAD,CAA/B,CAAjC;AACA,SAAOyB,OAAO,CAAC;AAAA,WAAMC,IAAI,CAACE,KAAL,CAAWJ,iBAAX,CAAN;AAAA,GAAD,EAAsC,CAACA,iBAAD,CAAtC,CAAd;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"next-sanity.esm.js","sources":["../src/client.ts","../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts"],"sourcesContent":["import sanityClient from '@sanity/client'\nimport type {ClientConfig, SanityClient} from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n","export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(\n projectId: string,\n abort: Aborter,\n token?: string\n): Promise<CurrentUser | null> {\n const headers = token ? {Authorization: `Bearer ${token}`} : undefined\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n headers,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {useState, useEffect, useMemo} from 'react'\nimport {GroqStore, Subscription} from '@sanity/groq-store'\nimport {ProjectConfig} from './types'\nimport {getCurrentUser} from './currentUser'\nimport {getAborter, Aborter} from './aborter'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n token,\n EventSource,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n token,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n token,\n EventSource,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n token?: string\n}) {\n const {getStore, projectId, query, initialData, enabled = false, token} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter, token)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled, projectId, token])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n"],"names":["createClient","config","sanityClient","MockAbortController","aborted","abort","_signal","getAborter","AbortController","createCurrentUserHook","projectId","useCurrentUser","getCurrentUser","token","headers","Authorization","undefined","fetch","credentials","signal","then","res","json","id","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","EMPTY_PARAMS","createPreviewSubscriptionHook","dataset","EventSource","documentLimit","store","usePreviewSubscription","query","options","params","initialData","enabled","useQuerySubscription","getStore","window","groqStore","Error","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs","setLoading","setData","useParams","subscription","user","console","warn","subscribe","result","finally","unsubscribe","stringifiedParams","useMemo","JSON","stringify","parse"],"mappings":";;;;SAGgBA,aAAaC;EAC3B,OAAOC,YAAY,CAACD,MAAD,CAAnB;AACD;;;;;;;;;;;;;;;;;;;;;ICAKE;EAAN;IACE,YAAA,GAAU;MAACC,OAAO,EAAE;KAApB;;;;;SAIAC,QAAA;IACE,KAAKC,OAAL,CAAaF,OAAb,GAAuB,IAAvB;;;;;SAJF;MACE,OAAO,KAAKE,OAAZ;;;;;;;AAOJ,SAAgBC;EACd,OAAO,OAAOC,eAAP,KAA2B,WAA3B,GACH,IAAIL,mBAAJ,EADG,GAEH,IAAIK,eAAJ,EAFJ;AAGD;;SCfeC;MAAuBC,iBAAAA;;EAErC,OAAO;IAAA,OAAMC,cAAc,CAACD,SAAD,CAApB;GAAP;AACD;AAED,SAAgBE,eACdF,WACAL,OACAQ;EAEA,IAAMC,OAAO,GAAGD,KAAK,GAAG;IAACE,aAAa,cAAYF;GAA7B,GAAwCG,SAA7D;EACA,OAAOC,KAAK,cAAYP,SAAZ,iCAAmD;IAC7DQ,WAAW,EAAE,SADgD;IAE7DC,MAAM,EAAEd,KAAK,CAACc,MAF+C;IAG7DL,OAAO,EAAPA;GAHU,CAAL,CAKJM,IALI,CAKC,UAACC,GAAD;IAAA,OAASA,GAAG,CAACC,IAAJ,EAAT;GALD,EAMJF,IANI,CAMC,UAACC,GAAD;IAAA,OAAUA,GAAG,QAAH,IAAAA,GAAG,CAAEE,EAAL,GAAUF,GAAV,GAAgB,IAA1B;GAND,CAAP;AAOD;;AAED,SAASV,cAAT,CAAwBD,SAAxB;EACE,gBAAwBc,QAAQ,EAAhC;MAAOC,IAAP;MAAaC,OAAb;;EACA,iBAA0BF,QAAQ,EAAlC;MAAOG,KAAP;MAAcC,QAAd;;EAEAC,SAAS,CAAC;IACR,IAAMC,OAAO,GAAGvB,UAAU,EA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MAAD,CAA/B,CAAjC;EACA,OAAOyB,OAAO,CAAC;IAAA,OAAMC,IAAI,CAACE,KAAL,CAAWJ,iBAAX,CAAN;GAAD,EAAsC,CAACA,iBAAD,CAAtC,CAAd;AACD;;;;"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
+
import type { Config } from '@sanity/groq-store/dist/typings/types';
|
|
2
|
+
export declare type GroqStoreEventSource = Config['EventSource'];
|
|
1
3
|
export interface ProjectConfig {
|
|
2
4
|
projectId: string;
|
|
3
5
|
dataset: string;
|
|
6
|
+
token?: string;
|
|
7
|
+
/** Must be provided when token is used in browser, as native EventSource does not support auth-headers. */
|
|
8
|
+
EventSource?: GroqStoreEventSource;
|
|
4
9
|
}
|
|
5
10
|
export interface CurrentUser {
|
|
6
11
|
id: string;
|
|
@@ -5,7 +5,7 @@ export interface SubscriptionOptions<R = any> {
|
|
|
5
5
|
params?: Params;
|
|
6
6
|
initialData?: R;
|
|
7
7
|
}
|
|
8
|
-
export declare function createPreviewSubscriptionHook({ projectId, dataset, documentLimit, }: ProjectConfig & {
|
|
8
|
+
export declare function createPreviewSubscriptionHook({ projectId, dataset, token, EventSource, documentLimit, }: ProjectConfig & {
|
|
9
9
|
documentLimit?: number;
|
|
10
10
|
}): <R = any>(query: string, options?: SubscriptionOptions<R>) => {
|
|
11
11
|
data: R;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-sanity",
|
|
3
3
|
"description": "Sanity.io toolkit for Next.js",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.0",
|
|
5
5
|
"author": "Sanity.io <hello@sanity.io>",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"sideEffects": false,
|
|
@@ -19,14 +19,14 @@
|
|
|
19
19
|
"start": "tsdx watch",
|
|
20
20
|
"build": "tsdx build",
|
|
21
21
|
"test": "tsdx test",
|
|
22
|
-
"lint": "
|
|
22
|
+
"lint": "eslint .",
|
|
23
23
|
"posttest": "npm run lint",
|
|
24
24
|
"prepublishOnly": "tsdx build && npm test",
|
|
25
25
|
"coverage": "tsdx test --coverage"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
28
|
"@sanity/client": "^3.3.0",
|
|
29
|
-
"@sanity/groq-store": "^0.
|
|
29
|
+
"@sanity/groq-store": "^0.4.0",
|
|
30
30
|
"groq": "^2.29.3"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
@@ -35,19 +35,19 @@
|
|
|
35
35
|
"@types/jest": "^27.0.0",
|
|
36
36
|
"@types/react": "^17.0.17",
|
|
37
37
|
"@types/react-dom": "^17.0.9",
|
|
38
|
-
"@typescript-eslint/eslint-plugin": "^
|
|
39
|
-
"@typescript-eslint/parser": "^
|
|
40
|
-
"eslint": "^
|
|
41
|
-
"eslint-config-prettier": "^
|
|
42
|
-
"eslint-config-react-app": "^
|
|
38
|
+
"@typescript-eslint/eslint-plugin": "^5.30.4",
|
|
39
|
+
"@typescript-eslint/parser": "^5.30.4",
|
|
40
|
+
"eslint": "^8.19.0",
|
|
41
|
+
"eslint-config-prettier": "^8.5.0",
|
|
42
|
+
"eslint-config-react-app": "^7.0.1",
|
|
43
43
|
"eslint-config-sanity": "^5.1.0",
|
|
44
|
-
"eslint-plugin-prettier": "^
|
|
45
|
-
"prettier": "^2.
|
|
44
|
+
"eslint-plugin-prettier": "^4.2.1",
|
|
45
|
+
"prettier": "^2.7.1",
|
|
46
46
|
"react": ">=17.0.2",
|
|
47
47
|
"react-dom": "^17.0.2",
|
|
48
48
|
"tsdx": "^0.14.1",
|
|
49
|
-
"tslib": "^2.
|
|
50
|
-
"typescript": "^4.
|
|
49
|
+
"tslib": "^2.4.0",
|
|
50
|
+
"typescript": "^4.7.4"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"react": ">=16.3.0"
|
package/src/currentUser.ts
CHANGED
|
@@ -3,13 +3,20 @@ import {CurrentUser} from './types'
|
|
|
3
3
|
import {getAborter, Aborter} from './aborter'
|
|
4
4
|
|
|
5
5
|
export function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {
|
|
6
|
+
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
6
7
|
return () => useCurrentUser(projectId)
|
|
7
8
|
}
|
|
8
9
|
|
|
9
|
-
export function getCurrentUser(
|
|
10
|
+
export function getCurrentUser(
|
|
11
|
+
projectId: string,
|
|
12
|
+
abort: Aborter,
|
|
13
|
+
token?: string
|
|
14
|
+
): Promise<CurrentUser | null> {
|
|
15
|
+
const headers = token ? {Authorization: `Bearer ${token}`} : undefined
|
|
10
16
|
return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {
|
|
11
17
|
credentials: 'include',
|
|
12
18
|
signal: abort.signal,
|
|
19
|
+
headers,
|
|
13
20
|
})
|
|
14
21
|
.then((res) => res.json())
|
|
15
22
|
.then((res) => (res?.id ? res : null))
|
package/src/types.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
|
+
import type {Config} from '@sanity/groq-store/dist/typings/types'
|
|
2
|
+
|
|
3
|
+
export type GroqStoreEventSource = Config['EventSource']
|
|
4
|
+
|
|
1
5
|
export interface ProjectConfig {
|
|
2
6
|
projectId: string
|
|
3
7
|
dataset: string
|
|
8
|
+
token?: string
|
|
9
|
+
/** Must be provided when token is used in browser, as native EventSource does not support auth-headers. */
|
|
10
|
+
EventSource?: GroqStoreEventSource
|
|
4
11
|
}
|
|
5
12
|
|
|
6
13
|
export interface CurrentUser {
|
package/src/useSubscription.ts
CHANGED
|
@@ -13,9 +13,12 @@ export interface SubscriptionOptions<R = any> {
|
|
|
13
13
|
initialData?: R
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
16
17
|
export function createPreviewSubscriptionHook({
|
|
17
18
|
projectId,
|
|
18
19
|
dataset,
|
|
20
|
+
token,
|
|
21
|
+
EventSource,
|
|
19
22
|
documentLimit = 3000,
|
|
20
23
|
}: ProjectConfig & {documentLimit?: number}) {
|
|
21
24
|
// Only construct/setup the store when `getStore()` is called
|
|
@@ -33,6 +36,7 @@ export function createPreviewSubscriptionHook({
|
|
|
33
36
|
params,
|
|
34
37
|
initialData: initialData as any,
|
|
35
38
|
enabled: enabled ? typeof window !== 'undefined' : false,
|
|
39
|
+
token,
|
|
36
40
|
})
|
|
37
41
|
}
|
|
38
42
|
|
|
@@ -51,6 +55,8 @@ export function createPreviewSubscriptionHook({
|
|
|
51
55
|
projectId,
|
|
52
56
|
dataset,
|
|
53
57
|
documentLimit,
|
|
58
|
+
token,
|
|
59
|
+
EventSource,
|
|
54
60
|
listen: true,
|
|
55
61
|
overlayDrafts: true,
|
|
56
62
|
subscriptionThrottleMs: 10,
|
|
@@ -68,8 +74,9 @@ function useQuerySubscription<R = any>(options: {
|
|
|
68
74
|
params: Params
|
|
69
75
|
initialData: R
|
|
70
76
|
enabled: boolean
|
|
77
|
+
token?: string
|
|
71
78
|
}) {
|
|
72
|
-
const {getStore, projectId, query, initialData, enabled = false} = options
|
|
79
|
+
const {getStore, projectId, query, initialData, enabled = false, token} = options
|
|
73
80
|
const [error, setError] = useState<Error>()
|
|
74
81
|
const [loading, setLoading] = useState(false)
|
|
75
82
|
const [data, setData] = useState<R>()
|
|
@@ -86,7 +93,7 @@ function useQuerySubscription<R = any>(options: {
|
|
|
86
93
|
|
|
87
94
|
const aborter = getAborter()
|
|
88
95
|
let subscription: Subscription | undefined
|
|
89
|
-
getCurrentUser(projectId, aborter)
|
|
96
|
+
getCurrentUser(projectId, aborter, token)
|
|
90
97
|
.then((user) => {
|
|
91
98
|
if (user) {
|
|
92
99
|
return
|
|
@@ -117,7 +124,7 @@ function useQuerySubscription<R = any>(options: {
|
|
|
117
124
|
|
|
118
125
|
aborter.abort()
|
|
119
126
|
}
|
|
120
|
-
}, [getStore, query, params, enabled])
|
|
127
|
+
}, [getStore, query, params, enabled, projectId, token])
|
|
121
128
|
|
|
122
129
|
return {
|
|
123
130
|
data: typeof data === 'undefined' ? initialData : data,
|