graphql-hooks
Advanced tools
Comparing version 4.3.0 to 4.4.0
@@ -6,2 +6,18 @@ # Change Log | ||
# [4.4.0](https://github.com/nearform/graphql-hooks/compare/graphql-hooks@4.3.0...graphql-hooks@4.4.0) (2020-01-21) | ||
### Bug Fixes | ||
* **deps:** update dependency extract-files to v7 ([#435](https://github.com/nearform/graphql-hooks/issues/435)) ([b5de6df](https://github.com/nearform/graphql-hooks/commit/b5de6dfe1d6bc5baf5e19cd6f1407426919319d2)) | ||
### Features | ||
* **TS:** Improve Typescript definition to allow custom type for 'GraphQLErrors' result ([#425](https://github.com/nearform/graphql-hooks/issues/425)) ([4352e63](https://github.com/nearform/graphql-hooks/commit/4352e63481ab907ac14f1215a734d94de970a6ae)) | ||
# [4.3.0](https://github.com/nearform/graphql-hooks/compare/graphql-hooks@4.2.0...graphql-hooks@4.3.0) (2019-12-12) | ||
@@ -8,0 +24,0 @@ |
@@ -1,1 +0,1 @@ | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],r):r((e=e||self).GraphQLHooks={},e.React)}(this,(function(e,r){"use strict";var t="default"in r?r.default:r;function n(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function o(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function i(e){for(var r=1;arguments.length>r;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?o(Object(t),!0).forEach((function(r){n(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):o(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}var a=t.createContext();a.displayName="ClientContext";var s=function(e){var r=e.name,t=e.type;this.uri=e.uri,this.name=r,this.type=t},u=function(e){return"undefined"!=typeof File&&e instanceof File||"undefined"!=typeof Blob&&e instanceof Blob||e instanceof s};var c=function(e){return u(e)||null!==e&&"object"==typeof e&&"function"==typeof e.pipe},f=function(){function e(e){if(void 0===e&&(e={}),!e.url)throw Error("GraphQLClient: config.url is required");if(e.fetch&&"function"!=typeof e.fetch)throw Error("GraphQLClient: config.fetch must be a function");if(!e.fetch&&!fetch)throw Error("GraphQLClient: fetch must be polyfilled or passed in new GraphQLClient({ fetch })");if(e.ssrMode&&!e.cache)throw Error("GraphQLClient: config.cache is required when in ssrMode");this.cache=e.cache,this.headers=e.headers||{},this.ssrMode=e.ssrMode,this.ssrPromises=[],this.url=e.url,this.fetch=e.fetch||fetch.bind(),this.fetchOptions=e.fetchOptions||{},this.FormData=e.FormData||("undefined"!=typeof FormData?FormData:void 0),this.logErrors=void 0===e.logErrors||e.logErrors,this.onError=e.onError,this.useGETForQueries=!0===e.useGETForQueries,this.subscriptionClient=e.subscriptionClient}var r=e.prototype;return r.setHeader=function(e,r){return this.headers[e]=r,this},r.setHeaders=function(e){return this.headers=e,this},r.removeHeader=function(e){return delete this.headers[e],this},r.logErrorResult=function(e){var r=e.result,t=e.operation;console.error("GraphQL Hooks Error"),console.groupCollapsed("---\x3e Full Error Details"),console.groupCollapsed("Operation:"),console.log(t),console.groupEnd();var n=r.error;n&&(n.fetchError&&(console.groupCollapsed("FETCH ERROR:"),console.log(n.fetchError),console.groupEnd()),n.httpError&&(console.groupCollapsed("HTTP ERROR:"),console.log(n.httpError),console.groupEnd()),n.graphQLErrors&&n.graphQLErrors.length>0&&(console.groupCollapsed("GRAPHQL ERROR:"),n.graphQLErrors.forEach((function(e){return console.log(e)})),console.groupEnd())),console.groupEnd()},r.generateResult=function(e){var r=e.fetchError,t=e.httpError,n=e.graphQLErrors,o=e.data;return!!(n&&n.length>0||r||t)?{data:o,error:{fetchError:r,httpError:t,graphQLErrors:n}}:{data:o}},r.getCacheKey=function(e,r){return void 0===r&&(r={}),{operation:e,fetchOptions:i({},this.fetchOptions,{},r.fetchOptionsOverrides)}},r.getCache=function(e){var r=this.cache?this.cache.get(e):null;if(r)return r},r.saveCache=function(e,r){this.cache&&this.cache.set(e,r)},r.getFetchOptions=function(e,r){void 0===r&&(r={});var t=i({method:"POST",headers:i({},this.headers)},this.fetchOptions,{},r);if("GET"===t.method)return t;var n=function e(r,t,n){var o;void 0===t&&(t=""),void 0===n&&(n=u);var i=new Map;function a(e,r){var t=i.get(r);t?t.push.apply(t,e):i.set(r,e)}if(n(r))o=null,a([t],r);else{var s=t?t+".":"";if("undefined"!=typeof FileList&&r instanceof FileList)o=Array.prototype.map.call(r,(function(e,r){return a([""+s+r],e),null}));else if(Array.isArray(r))o=r.map((function(r,t){var o=e(r,""+s+t,n);return o.files.forEach(a),o.clone}));else if(r&&r.constructor===Object)for(var c in o={},r){var f=e(r[c],""+s+c,n);f.files.forEach(a),o[c]=f.clone}else o=r}return{clone:o,files:i}}(e,"",c),o=n.files,a=JSON.stringify(n.clone);if(o.size){if(!this.FormData)throw Error("GraphQLClient: FormData must be polyfilled or passed in new GraphQLClient({ FormData })");var s=new this.FormData;s.append("operations",a);var f={},l=0;o.forEach((function(e){f[++l]=e})),s.append("map",JSON.stringify(f)),l=0,o.forEach((function(e,r){s.append(""+ ++l,r,r.name)})),t.body=s}else t.headers["Content-Type"]="application/json",t.body=a;return t},r.request=function(e,r){var t=this;void 0===r&&(r={});var n=this.url;"GET"===this.getFetchOptions(e,r.fetchOptionsOverrides).method&&(n=n+"?"+Object.entries(e).filter((function(e){return!!e[1]})).map((function(e){var r=e[0],t=e[1];return"variables"===r&&(t=JSON.stringify(t)),r+"="+encodeURIComponent(t)})).join("&"));return this.fetch(n,this.getFetchOptions(e,r.fetchOptionsOverrides)).then((function(e){return e.ok?e.json().then((function(e){return t.generateResult({graphQLErrors:e.errors,data:e.data})})):e.text().then((function(r){return t.generateResult({httpError:{status:e.status,statusText:e.statusText,body:r}})}))})).catch((function(e){return t.generateResult({fetchError:e})})).then((function(r){return r.error&&(t.logErrors&&t.logErrorResult({result:r,operation:e}),t.onError&&t.onError({result:r,operation:e})),r}))},r.createSubscription=function(e){return this.subscriptionClient.request(e)},e}();var l={RESET_STATE:"RESET_STATE",LOADING:"LOADING",CACHE_HIT:"CACHE_HIT",REQUEST_RESULT:"REQUEST_RESULT"};function h(e,r){switch(r.type){case l.RESET_STATE:return r.initialState;case l.LOADING:return e.loading?e:i({},e,{loading:!0});case l.CACHE_HIT:return e.cacheHit&&!r.resetState?e:i({},r.result,{cacheHit:!0,loading:!1});case l.REQUEST_RESULT:return i({},r.result,{data:e.data&&r.result.data&&r.updateData?r.updateData(e.data,r.result.data):r.result.data,cacheHit:!1,loading:!1});default:return e}}function p(e,r){var n=t.useRef();return function e(r,t){var n,o;if(r===t)return!0;if(r&&t&&(n=r.constructor)===t.constructor){if(n===Date)return r.getTime()===t.getTime();if(n===RegExp)return""+r==""+t;if(n===Array&&(o=r.length)===t.length){for(;o--&&e(r[o],t[o]););return-1===o}if(n===Object){if(Object.keys(r).length!==Object.keys(t).length)return!1;for(o in r)if(!(o in t&&e(r[o],t[o])))return!1;return!0}}return r!=r&&t!=t}(r,n.current)||(n.current=r),t.useCallback(e,n.current)}function d(e,r){if(void 0===r&&(r={}),"string"!=typeof e)throw Error("Your query must be a string. If you are using the `gql` template literal from graphql-tag, remove it from your query.");var n=t.useContext(a),o=t.useRef(!0),s=t.useRef(null),u={query:e,variables:r.variables,operationName:r.operationName};n.useGETForQueries&&!r.isMutation&&(r.fetchOptionsOverrides=i({},r.fetchOptionsOverrides,{method:"GET"}));var c=n.getCacheKey(u,r),f=r.isMutation||r.isManual,d=r.skipCache||!n.cache?null:n.cache.get(c),E=i({},d,{cacheHit:!!d,loading:!f&&!d}),g=t.useReducer(h,E),v=g[0],y=g[1],b=JSON.stringify(c);t.useEffect((function(){r.updateData||y({type:l.RESET_STATE,initialState:E})}),[b]),t.useEffect((function(){return o.current=!0,function(){o.current=!1}}),[]);var O=p((function(e){if(!o.current)return Promise.resolve();var t=i({},r,{},e),a=i({},u,{variables:t.variables,operationName:t.operationName}),c=n.getCacheKey(a,t);s.current=c;var f=t.skipCache?null:n.getCache(c);return f?(y({type:l.CACHE_HIT,result:f,resetState:b!==JSON.stringify(v.cacheKey)}),Promise.resolve(f)):(y({type:l.LOADING}),n.request(a,t).then((function(e){if(t.updateData&&"function"!=typeof t.updateData)throw Error("options.updateData must be a function");var r=i({},e);if(t.useCache&&(r.useCache=!0,r.cacheKey=c,n.ssrMode)){var a={data:t.updateData?t.updateData(v.data,r.data):r.data};n.saveCache(c,a)}return o.current&&c===s.current&&y({type:l.REQUEST_RESULT,updateData:t.updateData,result:r}),e})))}),[n,r,u]);return t.useEffect((function(){v.useCache&&n.saveCache(v.cacheKey,v)}),[n,v]),[O,v]}var E={useCache:!0};e.ClientContext=a,e.GraphQLClient=f,e.useClientRequest=d,e.useManualQuery=function(e,r){return d(e,i({useCache:!0,isManual:!0},r))},e.useMutation=function(e,r){return d(e,i({isMutation:!0},r))},e.useQuery=function(e,r){void 0===r&&(r={});var n=i({},E,{},r),o=t.useContext(a),s=t.useState(!1),u=s[0],c=s[1],f=d(e,n),l=f[0],h=f[1];if(o.ssrMode&&!1!==r.ssr&&!u&&!r.skipCache){if(!h.data&&!h.error){var p=l();o.ssrPromises.push(p)}c(!0)}var g=JSON.stringify(n);return t.useEffect((function(){l()}),[e,g]),i({},h,{refetch:t.useCallback((function(e){return void 0===e&&(e={}),l(i({skipCache:!0,updateData:function(e,r){return r}},e))}),[l])})},e.useSubscription=function(e,t){var n=r.useRef(t);n.current=t;var o=r.useContext(a),i={query:e.query,variables:e.variables};r.useEffect((function(){var e=o.createSubscription(i).subscribe({next:function(e){n.current(e)},error:function(){e.unsubscribe()},complete:function(){e.unsubscribe()}});return function(){e.unsubscribe()}}),[])},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],r):r((e=e||self).GraphQLHooks={},e.React)}(this,(function(e,r){"use strict";var t="default"in r?r.default:r;function n(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function o(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function i(e){for(var r=1;arguments.length>r;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?o(Object(t),!0).forEach((function(r){n(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):o(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}var a=t.createContext();a.displayName="ClientContext";var s=function(e){var r=e.name,t=e.type;this.uri=e.uri,this.name=r,this.type=t},u=function(e){return"undefined"!=typeof File&&e instanceof File||"undefined"!=typeof Blob&&e instanceof Blob||e instanceof s};var c=function(e){return u(e)||null!==e&&"object"==typeof e&&"function"==typeof e.pipe},f=function(){function e(e){if(void 0===e&&(e={}),!e.url)throw Error("GraphQLClient: config.url is required");if(e.fetch&&"function"!=typeof e.fetch)throw Error("GraphQLClient: config.fetch must be a function");if(!e.fetch&&!fetch)throw Error("GraphQLClient: fetch must be polyfilled or passed in new GraphQLClient({ fetch })");if(e.ssrMode&&!e.cache)throw Error("GraphQLClient: config.cache is required when in ssrMode");this.cache=e.cache,this.headers=e.headers||{},this.ssrMode=e.ssrMode,this.ssrPromises=[],this.url=e.url,this.fetch=e.fetch||fetch.bind(),this.fetchOptions=e.fetchOptions||{},this.FormData=e.FormData||("undefined"!=typeof FormData?FormData:void 0),this.logErrors=void 0===e.logErrors||e.logErrors,this.onError=e.onError,this.useGETForQueries=!0===e.useGETForQueries,this.subscriptionClient=e.subscriptionClient}var r=e.prototype;return r.setHeader=function(e,r){return this.headers[e]=r,this},r.setHeaders=function(e){return this.headers=e,this},r.removeHeader=function(e){return delete this.headers[e],this},r.logErrorResult=function(e){var r=e.result,t=e.operation;console.error("GraphQL Hooks Error"),console.groupCollapsed("---\x3e Full Error Details"),console.groupCollapsed("Operation:"),console.log(t),console.groupEnd();var n=r.error;n&&(n.fetchError&&(console.groupCollapsed("FETCH ERROR:"),console.log(n.fetchError),console.groupEnd()),n.httpError&&(console.groupCollapsed("HTTP ERROR:"),console.log(n.httpError),console.groupEnd()),n.graphQLErrors&&n.graphQLErrors.length>0&&(console.groupCollapsed("GRAPHQL ERROR:"),n.graphQLErrors.forEach((function(e){return console.log(e)})),console.groupEnd())),console.groupEnd()},r.generateResult=function(e){var r=e.fetchError,t=e.httpError,n=e.graphQLErrors,o=e.data;return!!(n&&n.length>0||r||t)?{data:o,error:{fetchError:r,httpError:t,graphQLErrors:n}}:{data:o}},r.getCacheKey=function(e,r){return void 0===r&&(r={}),{operation:e,fetchOptions:i({},this.fetchOptions,{},r.fetchOptionsOverrides)}},r.getCache=function(e){var r=this.cache?this.cache.get(e):null;if(r)return r},r.saveCache=function(e,r){this.cache&&this.cache.set(e,r)},r.getFetchOptions=function(e,r){void 0===r&&(r={});var t=i({method:"POST",headers:i({},this.headers)},this.fetchOptions,{},r);if("GET"===t.method)return t;var n=function e(r,t,n){var o;void 0===t&&(t=""),void 0===n&&(n=u);var i=new Map;function a(e,r){var t=i.get(r);t?t.push.apply(t,e):i.set(r,e)}if(n(r))o=null,a([t],r);else{var s=t?t+".":"";if("undefined"!=typeof FileList&&r instanceof FileList)o=Array.prototype.map.call(r,(function(e,r){return a([""+s+r],e),null}));else if(Array.isArray(r))o=r.map((function(r,t){var o=e(r,""+s+t,n);return o.files.forEach(a),o.clone}));else if(r&&r.constructor===Object)for(var c in o={},r){var f=e(r[c],""+s+c,n);f.files.forEach(a),o[c]=f.clone}else o=r}return{clone:o,files:i}}(e,"",c),o=n.files,a=JSON.stringify(n.clone);if(o.size){if(!this.FormData)throw Error("GraphQLClient: FormData must be polyfilled or passed in new GraphQLClient({ FormData })");var s=new this.FormData;s.append("operations",a);var f={},l=0;o.forEach((function(e){f[++l]=e})),s.append("map",JSON.stringify(f)),l=0,o.forEach((function(e,r){s.append(""+ ++l,r,r.name)})),t.body=s}else t.headers["Content-Type"]="application/json",t.body=a;return t},r.request=function(e,r){var t=this;void 0===r&&(r={});var n=this.url;"GET"===this.getFetchOptions(e,r.fetchOptionsOverrides).method&&(n=n+"?"+Object.entries(e).filter((function(e){return!!e[1]})).map((function(e){var r=e[0],t=e[1];return"variables"===r&&(t=JSON.stringify(t)),r+"="+encodeURIComponent(t)})).join("&"));return this.fetch(n,this.getFetchOptions(e,r.fetchOptionsOverrides)).then((function(e){return e.ok?e.json().then((function(e){return t.generateResult({graphQLErrors:e.errors,data:e.data})})):e.text().then((function(r){return t.generateResult({httpError:{status:e.status,statusText:e.statusText,body:r}})}))})).catch((function(e){return t.generateResult({fetchError:e})})).then((function(r){return r.error&&(t.logErrors&&t.logErrorResult({result:r,operation:e}),t.onError&&t.onError({result:r,operation:e})),r}))},r.createSubscription=function(e){return this.subscriptionClient.request(e)},e}();var l="RESET_STATE",h="LOADING",p="CACHE_HIT",d="REQUEST_RESULT";function g(e,r){switch(r.type){case l:return r.initialState;case h:return e.loading?e:i({},e,{loading:!0});case p:return e.cacheHit&&!r.resetState?e:i({},r.result,{cacheHit:!0,loading:!1});case d:return i({},r.result,{data:e.data&&r.result.data&&r.updateData?r.updateData(e.data,r.result.data):r.result.data,cacheHit:!1,loading:!1});default:return e}}function v(e,r){var n=t.useRef();return function e(r,t){var n,o;if(r===t)return!0;if(r&&t&&(n=r.constructor)===t.constructor){if(n===Date)return r.getTime()===t.getTime();if(n===RegExp)return""+r==""+t;if(n===Array&&(o=r.length)===t.length){for(;o--&&e(r[o],t[o]););return-1===o}if(n===Object){if(Object.keys(r).length!==Object.keys(t).length)return!1;for(o in r)if(!(o in t&&e(r[o],t[o])))return!1;return!0}}return r!=r&&t!=t}(r,n.current)||(n.current=r),t.useCallback(e,n.current)}function E(e,r){if(void 0===r&&(r={}),"string"!=typeof e)throw Error("Your query must be a string. If you are using the `gql` template literal from graphql-tag, remove it from your query.");var n=t.useContext(a),o=t.useRef(!0),s=t.useRef(null),u={query:e,variables:r.variables,operationName:r.operationName};n.useGETForQueries&&!r.isMutation&&(r.fetchOptionsOverrides=i({},r.fetchOptionsOverrides,{method:"GET"}));var c=n.getCacheKey(u,r),f=r.isMutation||r.isManual,E=r.skipCache||!n.cache?null:n.cache.get(c),y=i({},E,{cacheHit:!!E,loading:!f&&!E}),b=t.useReducer(g,y),O=b[0],C=b[1],m=JSON.stringify(c);t.useEffect((function(){r.updateData||C({type:l,initialState:y})}),[m]),t.useEffect((function(){return o.current=!0,function(){o.current=!1}}),[]);var R=v((function(e){if(!o.current)return Promise.resolve();var t=i({},r,{},e),a=i({},u,{variables:t.variables,operationName:t.operationName}),c=n.getCacheKey(a,t);s.current=c;var f=t.skipCache?null:n.getCache(c);return f?(C({type:p,result:f,resetState:m!==JSON.stringify(O.cacheKey)}),Promise.resolve(f)):(C({type:h}),n.request(a,t).then((function(e){if(t.updateData&&"function"!=typeof t.updateData)throw Error("options.updateData must be a function");var r=i({},e);if(t.useCache&&(r.useCache=!0,r.cacheKey=c,n.ssrMode)){var a={data:t.updateData?t.updateData(O.data,r.data):r.data};n.saveCache(c,a)}return o.current&&c===s.current&&C({type:d,updateData:t.updateData,result:r}),e})))}),[n,r,u]);return t.useEffect((function(){O.useCache&&n.saveCache(O.cacheKey,O)}),[n,O]),[R,O]}var y={useCache:!0};e.ClientContext=a,e.GraphQLClient=f,e.useClientRequest=E,e.useManualQuery=function(e,r){return E(e,i({useCache:!0,isManual:!0},r))},e.useMutation=function(e,r){return E(e,i({isMutation:!0},r))},e.useQuery=function(e,r){void 0===r&&(r={});var n=i({},y,{},r),o=t.useContext(a),s=t.useState(!1),u=s[0],c=s[1],f=E(e,n),l=f[0],h=f[1];if(o.ssrMode&&!1!==r.ssr&&!u&&!r.skipCache){if(!h.data&&!h.error){var p=l();o.ssrPromises.push(p)}c(!0)}var d=JSON.stringify(n);return t.useEffect((function(){l()}),[e,d]),i({},h,{refetch:t.useCallback((function(e){return void 0===e&&(e={}),l(i({skipCache:!0,updateData:function(e,r){return r}},e))}),[l])})},e.useSubscription=function(e,t){var n=r.useRef(t);n.current=t;var o=r.useContext(a),i={query:e.query,variables:e.variables};r.useEffect((function(){var e=o.createSubscription(i).subscribe({next:function(e){n.current(e)},error:function(){e.unsubscribe()},complete:function(){e.unsubscribe()}});return function(){e.unsubscribe()}}),[])},Object.defineProperty(e,"__esModule",{value:!0})})); |
@@ -22,7 +22,7 @@ import * as React from 'react' | ||
removeHeader(key: string): GraphQLClient | ||
logErrorResult({ | ||
logErrorResult<ResponseData, TGraphQLError>({ | ||
result, | ||
operation | ||
}: { | ||
result: Result | ||
result: Result<ResponseData, TGraphQLError> | ||
operation: Operation | ||
@@ -35,28 +35,41 @@ }): void | ||
getFetchOptions(operation: Operation, fetchOptionsOverrides?: object): object | ||
request<ResponseData>(operation: Operation, options?: object): | ||
Promise<Result<ResponseData>> | ||
request<ResponseData, TGraphQLError>( | ||
operation: Operation, | ||
options?: object | ||
): Promise<Result<ResponseData, TGraphQLError>> | ||
} | ||
export function useClientRequest<ResponseData = any, Variables = object>( | ||
export function useClientRequest< | ||
ResponseData = any, | ||
Variables = object, | ||
TGraphQLError = object | ||
>( | ||
query: string, | ||
options?: UseClientRequestOptions<Variables> | ||
): [FetchData<ResponseData, Variables>, UseClientRequestResult<ResponseData>] | ||
): [ | ||
FetchData<ResponseData, Variables, TGraphQLError>, | ||
UseClientRequestResult<ResponseData, TGraphQLError> | ||
] | ||
export function useQuery<ResponseData = any, Variables = object>( | ||
export function useQuery< | ||
ResponseData = any, | ||
Variables = object, | ||
TGraphQLError = object | ||
>( | ||
query: string, | ||
options?: UseQueryOptions<Variables> | ||
): UseQueryResult<ResponseData, Variables> | ||
): UseQueryResult<ResponseData, Variables, TGraphQLError> | ||
export function useManualQuery<ResponseData = any, Variables = object>( | ||
export function useManualQuery<ResponseData = any, Variables = object, TGraphQLError = object>( | ||
query: string, | ||
options?: UseClientRequestOptions<Variables> | ||
): [FetchData<ResponseData, Variables>, UseClientRequestResult<ResponseData>] | ||
): [FetchData<ResponseData, Variables, TGraphQLError>, UseClientRequestResult<ResponseData, TGraphQLError>] | ||
export function useMutation<ResponseData = any, Variables = object>( | ||
export function useMutation<ResponseData = any, Variables = object, TGraphQLError = object>( | ||
query: string, | ||
options?: UseClientRequestOptions<Variables> | ||
): [FetchData<ResponseData, Variables>, UseClientRequestResult<ResponseData>] | ||
): [FetchData<ResponseData, Variables, TGraphQLError>, UseClientRequestResult<ResponseData, TGraphQLError>] | ||
export interface SubscriptionRequest { | ||
query: string, | ||
query: string | ||
variables: object | ||
@@ -115,11 +128,11 @@ } | ||
interface APIError { | ||
interface APIError<TGraphQLError = object> { | ||
fetchError?: Error | ||
httpError?: HttpError | ||
graphQLErrors?: object[] | ||
graphQLErrors?: TGraphQLError[] | ||
} | ||
interface Result<ResponseData = any> { | ||
interface Result<ResponseData = any, TGraphQLError = object> { | ||
data?: ResponseData | ||
error?: APIError | ||
error?: APIError<TGraphQLError> | ||
} | ||
@@ -143,19 +156,22 @@ | ||
interface UseClientRequestResult<ResponseData> { | ||
interface UseClientRequestResult<ResponseData, TGraphQLError> { | ||
loading: boolean | ||
cacheHit: boolean | ||
data: ResponseData | ||
error?: APIError | ||
error?: APIError<TGraphQLError> | ||
} | ||
interface UseQueryResult<ResponseData, Variables = object> | ||
extends UseClientRequestResult<ResponseData> { | ||
interface UseQueryResult< | ||
ResponseData, | ||
Variables = object, | ||
TGraphQLError = object | ||
> extends UseClientRequestResult<ResponseData, TGraphQLError> { | ||
refetch( | ||
options?: UseQueryOptions<Variables> | ||
): Promise<UseClientRequestResult<ResponseData>> | ||
): Promise<UseClientRequestResult<ResponseData, TGraphQLError>> | ||
} | ||
type FetchData<ResponseData, Variables = object> = ( | ||
type FetchData<ResponseData, Variables = object, TGraphQLError = object> = ( | ||
options?: UseClientRequestOptions<Variables> | ||
) => Promise<UseClientRequestResult<ResponseData>> | ||
) => Promise<UseClientRequestResult<ResponseData, TGraphQLError>> | ||
@@ -162,0 +178,0 @@ interface CacheKeyObject { |
{ | ||
"name": "graphql-hooks", | ||
"version": "4.3.0", | ||
"version": "4.4.0", | ||
"description": "Graphql Hooks", | ||
@@ -38,3 +38,3 @@ "main": "lib/graphql-hooks.js", | ||
"dequal": "^1.0.0", | ||
"extract-files": "^6.0.0" | ||
"extract-files": "^7.0.0" | ||
}, | ||
@@ -45,5 +45,5 @@ "devDependencies": { | ||
"formdata-node": "^2.0.0", | ||
"graphql-hooks-memcache": "^1.3.0", | ||
"graphql-hooks-memcache": "^1.3.1", | ||
"graphql-hooks-ssr": "^1.1.5", | ||
"jest-fetch-mock": "^2.1.2", | ||
"jest-fetch-mock": "^3.0.0", | ||
"react": "^16.12.0", | ||
@@ -62,3 +62,3 @@ "react-dom": "^16.12.0", | ||
"homepage": "https://github.com/nearform/graphql-hooks#readme", | ||
"gitHead": "b562a414d019cda4c7acd98554e99004bc52c582" | ||
"gitHead": "9c6b91200ca8bad12521586aeba3bbd6f97ecadf" | ||
} |
@@ -641,4 +641,61 @@ # graphql-hooks | ||
Coming soon! | ||
You can have access the to the graphql-hooks client context by using the React's new context API. `ClientContext` is actually the result of `React.createContext()`. | ||
**Login example** | ||
```jsx | ||
import React, { useState, useContext } from 'react' | ||
import { useMutation, ClientContext } from 'graphql-hooks' | ||
const LOGIN_MUTATION = `mutation LoginUser (name: String!, password: String!) { | ||
loginUser(name: $name, password: $password) { | ||
token | ||
} | ||
}` | ||
const Login = () => { | ||
const client = useContext(ClientContext) | ||
const [loginUserMutation] = useMutation(LOGIN_MUTATION) | ||
const [userName, setUserName] = useState() | ||
const [password, setPassword] = useState() | ||
const handleLogin = async e => { | ||
e.preventDefault() | ||
const { data, error } = await loginUserMutation({ | ||
variables: { userName, password } | ||
}) | ||
if (error) { | ||
// your code to handle login error | ||
} else { | ||
const { token } = data.loginUser | ||
client.setHeader('Authorization', `Bearer ${token}`) | ||
// your code to handle token in browser and login redirection | ||
} | ||
} | ||
return ( | ||
<form onSubmit={handleLogin}> | ||
User Name:{' '} | ||
<input | ||
type={'text'} | ||
value={userName} | ||
onChange={e => setUserName(e.target.value)} | ||
/> | ||
PassWord: <input | ||
type={'password'} | ||
value={password} | ||
onChange={e => setPassword(e.target.value)} | ||
/> | ||
<input type={'submit'} value={'Login'} /> | ||
</form> | ||
) | ||
} | ||
export default Login | ||
``` | ||
In the above example we use `useContext()` hook to get access to the graphql-hooks clientContext. | ||
Then we request the token from the server by performing the `loginUser` mutation. | ||
In the case the login is success we set the token to the client's header (`client.setHeader`), otherwise we need to handle the error. | ||
For more information about graphql-hooks clientContext refer to [GraphQLClient](#GraphQLClient) section. | ||
## Fragments | ||
@@ -892,2 +949,3 @@ | ||
<td align="center"><a href="https://github.com/lynxtaa"><img src="https://avatars1.githubusercontent.com/u/22496946?v=4" width="100px;" alt=""/><br /><sub><b>Alex Kondratyuk</b></sub></a><br /><a href="https://github.com/nearform/graphql-hooks/commits?author=lynxtaa" title="Code">💻</a> <a href="https://github.com/nearform/graphql-hooks/commits?author=lynxtaa" title="Tests">⚠️</a> <a href="https://github.com/nearform/graphql-hooks/commits?author=lynxtaa" title="Documentation">📖</a> <a href="https://github.com/nearform/graphql-hooks/issues?q=author%3Alynxtaa" title="Bug reports">🐛</a></td> | ||
<td align="center"><a href="https://github.com/cepelinc"><img src="https://avatars1.githubusercontent.com/u/25613873?v=4" width="100px;" alt=""/><br /><sub><b>Matias Cepeda</b></sub></a><br /><a href="https://github.com/nearform/graphql-hooks/commits?author=cepelinc" title="Documentation">📖</a></td> | ||
</tr> | ||
@@ -894,0 +952,0 @@ </table> |
Sorry, the diff of this file is not supported yet
147219
2396
957
+ Addedextract-files@7.0.0(transitive)
- Removedextract-files@6.0.0(transitive)
Updatedextract-files@^7.0.0