diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9ad30e6a04..ee522ce49c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -149,7 +149,17 @@ jobs: fail-fast: false matrix: node: ['18.x'] - example: ['cra4', 'cra5', 'next', 'vite', 'node-standard', 'node-esm', 'react-native', 'expo'] + example: + [ + 'cra4', + 'cra5', + 'next', + 'vite', + 'node-standard', + 'node-esm', + 'react-native', + 'expo', + ] defaults: run: working-directory: ./examples/publish-ci/${{ matrix.example }} diff --git a/.prettierrc.json b/.prettierrc.json index 61ca55dbb6..6ef9e41d05 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -3,4 +3,3 @@ "singleQuote": true, "endOfLine": "auto" } - \ No newline at end of file diff --git a/.yarn/releases/yarn-3.2.4.cjs b/.yarn/releases/yarn-3.2.4.cjs index 38f17fd49e..f607954682 100644 --- a/.yarn/releases/yarn-3.2.4.cjs +++ b/.yarn/releases/yarn-3.2.4.cjs @@ -1,7 +1,7 @@ #!/usr/bin/env node /* eslint-disable */ //prettier-ignore -(()=>{var nfe=Object.create;var HS=Object.defineProperty;var sfe=Object.getOwnPropertyDescriptor;var ofe=Object.getOwnPropertyNames;var afe=Object.getPrototypeOf,Afe=Object.prototype.hasOwnProperty;var J=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+r+'" is not supported')});var y=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ht=(r,e)=>{for(var t in e)HS(r,t,{get:e[t],enumerable:!0})},lfe=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ofe(e))!Afe.call(r,n)&&n!==t&&HS(r,n,{get:()=>e[n],enumerable:!(i=sfe(e,n))||i.enumerable});return r};var ne=(r,e,t)=>(t=r!=null?nfe(afe(r)):{},lfe(e||!r||!r.__esModule?HS(t,"default",{value:r,enumerable:!0}):t,r));var ZU=y(($_e,_U)=>{_U.exports=XU;XU.sync=Dfe;var zU=J("fs");function Pfe(r,e){var t=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!t||(t=t.split(";"),t.indexOf("")!==-1))return!0;for(var i=0;i{r1.exports=e1;e1.sync=kfe;var $U=J("fs");function e1(r,e,t){$U.stat(r,function(i,n){t(i,i?!1:t1(n,e))})}function kfe(r,e){return t1($U.statSync(r),e)}function t1(r,e){return r.isFile()&&Rfe(r,e)}function Rfe(r,e){var t=r.mode,i=r.uid,n=r.gid,s=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),o=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),l=parseInt("010",8),c=parseInt("001",8),u=a|l,g=t&c||t&l&&n===o||t&a&&i===s||t&u&&s===0;return g}});var s1=y((rZe,n1)=>{var tZe=J("fs"),RI;process.platform==="win32"||global.TESTING_WINDOWS?RI=ZU():RI=i1();n1.exports=nv;nv.sync=Ffe;function nv(r,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,n){nv(r,e||{},function(s,o){s?n(s):i(o)})})}RI(r,e||{},function(i,n){i&&(i.code==="EACCES"||e&&e.ignoreErrors)&&(i=null,n=!1),t(i,n)})}function Ffe(r,e){try{return RI.sync(r,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}});var g1=y((iZe,u1)=>{var Xg=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",o1=J("path"),Nfe=Xg?";":":",a1=s1(),A1=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),l1=(r,e)=>{let t=e.colon||Nfe,i=r.match(/\//)||Xg&&r.match(/\\/)?[""]:[...Xg?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],n=Xg?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Xg?n.split(t):[""];return Xg&&r.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:i,pathExt:s,pathExtExe:n}},c1=(r,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});let{pathEnv:i,pathExt:n,pathExtExe:s}=l1(r,e),o=[],a=c=>new Promise((u,g)=>{if(c===i.length)return e.all&&o.length?u(o):g(A1(r));let f=i[c],h=/^".*"$/.test(f)?f.slice(1,-1):f,p=o1.join(h,r),m=!h&&/^\.[\\\/]/.test(r)?r.slice(0,2)+p:p;u(l(m,c,0))}),l=(c,u,g)=>new Promise((f,h)=>{if(g===n.length)return f(a(u+1));let p=n[g];a1(c+p,{pathExt:s},(m,w)=>{if(!m&&w)if(e.all)o.push(c+p);else return f(c+p);return f(l(c,u,g+1))})});return t?a(0).then(c=>t(null,c),t):a(0)},Lfe=(r,e)=>{e=e||{};let{pathEnv:t,pathExt:i,pathExtExe:n}=l1(r,e),s=[];for(let o=0;o{"use strict";var f1=(r={})=>{let e=r.env||process.env;return(r.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(i=>i.toUpperCase()==="PATH")||"Path"};sv.exports=f1;sv.exports.default=f1});var m1=y((sZe,C1)=>{"use strict";var p1=J("path"),Tfe=g1(),Ofe=h1();function d1(r,e){let t=r.options.env||process.env,i=process.cwd(),n=r.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(r.options.cwd)}catch{}let o;try{o=Tfe.sync(r.command,{path:t[Ofe({env:t})],pathExt:e?p1.delimiter:void 0})}catch{}finally{s&&process.chdir(i)}return o&&(o=p1.resolve(n?r.options.cwd:"",o)),o}function Mfe(r){return d1(r)||d1(r,!0)}C1.exports=Mfe});var E1=y((oZe,av)=>{"use strict";var ov=/([()\][%!^"`<>&|;, *?])/g;function Kfe(r){return r=r.replace(ov,"^$1"),r}function Ufe(r,e){return r=`${r}`,r=r.replace(/(\\*)"/g,'$1$1\\"'),r=r.replace(/(\\*)$/,"$1$1"),r=`"${r}"`,r=r.replace(ov,"^$1"),e&&(r=r.replace(ov,"^$1")),r}av.exports.command=Kfe;av.exports.argument=Ufe});var y1=y((aZe,I1)=>{"use strict";I1.exports=/^#!(.*)/});var B1=y((AZe,w1)=>{"use strict";var Hfe=y1();w1.exports=(r="")=>{let e=r.match(Hfe);if(!e)return null;let[t,i]=e[0].replace(/#! ?/,"").split(" "),n=t.split("/").pop();return n==="env"?i:i?`${n} ${i}`:n}});var b1=y((lZe,Q1)=>{"use strict";var Av=J("fs"),Gfe=B1();function Yfe(r){let t=Buffer.alloc(150),i;try{i=Av.openSync(r,"r"),Av.readSync(i,t,0,150,0),Av.closeSync(i)}catch{}return Gfe(t.toString())}Q1.exports=Yfe});var P1=y((cZe,x1)=>{"use strict";var jfe=J("path"),S1=m1(),v1=E1(),qfe=b1(),Jfe=process.platform==="win32",Wfe=/\.(?:com|exe)$/i,zfe=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Vfe(r){r.file=S1(r);let e=r.file&&qfe(r.file);return e?(r.args.unshift(r.file),r.command=e,S1(r)):r.file}function Xfe(r){if(!Jfe)return r;let e=Vfe(r),t=!Wfe.test(e);if(r.options.forceShell||t){let i=zfe.test(e);r.command=jfe.normalize(r.command),r.command=v1.command(r.command),r.args=r.args.map(s=>v1.argument(s,i));let n=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${n}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}function _fe(r,e,t){e&&!Array.isArray(e)&&(t=e,e=null),e=e?e.slice(0):[],t=Object.assign({},t);let i={command:r,args:e,options:t,file:void 0,original:{command:r,args:e}};return t.shell?i:Xfe(i)}x1.exports=_fe});var R1=y((uZe,k1)=>{"use strict";var lv=process.platform==="win32";function cv(r,e){return Object.assign(new Error(`${e} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${r.command}`,path:r.command,spawnargs:r.args})}function Zfe(r,e){if(!lv)return;let t=r.emit;r.emit=function(i,n){if(i==="exit"){let s=D1(n,e,"spawn");if(s)return t.call(r,"error",s)}return t.apply(r,arguments)}}function D1(r,e){return lv&&r===1&&!e.file?cv(e.original,"spawn"):null}function $fe(r,e){return lv&&r===1&&!e.file?cv(e.original,"spawnSync"):null}k1.exports={hookChildProcess:Zfe,verifyENOENT:D1,verifyENOENTSync:$fe,notFoundError:cv}});var fv=y((gZe,_g)=>{"use strict";var F1=J("child_process"),uv=P1(),gv=R1();function N1(r,e,t){let i=uv(r,e,t),n=F1.spawn(i.command,i.args,i.options);return gv.hookChildProcess(n,i),n}function ehe(r,e,t){let i=uv(r,e,t),n=F1.spawnSync(i.command,i.args,i.options);return n.error=n.error||gv.verifyENOENTSync(n.status,i),n}_g.exports=N1;_g.exports.spawn=N1;_g.exports.sync=ehe;_g.exports._parse=uv;_g.exports._enoent=gv});var T1=y((fZe,L1)=>{"use strict";function the(r,e){function t(){this.constructor=r}t.prototype=e.prototype,r.prototype=new t}function cc(r,e,t,i){this.message=r,this.expected=e,this.found=t,this.location=i,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,cc)}the(cc,Error);cc.buildMessage=function(r,e){var t={literal:function(c){return'"'+n(c.text)+'"'},class:function(c){var u="",g;for(g=0;g0){for(g=1,f=1;g>",te=de(">>",!1),me=">&",tt=de(">&",!1),Rt=">",It=de(">",!1),Kr="<<<",oi=de("<<<",!1),pi="<&",pr=de("<&",!1),di="<",ai=de("<",!1),Os=function(C){return{type:"argument",segments:[].concat(...C)}},dr=function(C){return C},Bi="$'",_n=de("$'",!1),ga="'",CA=de("'",!1),Dg=function(C){return[{type:"text",text:C}]},Zn='""',mA=de('""',!1),fa=function(){return{type:"text",text:""}},jp='"',EA=de('"',!1),IA=function(C){return C},wr=function(C){return{type:"arithmetic",arithmetic:C,quoted:!0}},zl=function(C){return{type:"shell",shell:C,quoted:!0}},kg=function(C){return{type:"variable",...C,quoted:!0}},mo=function(C){return{type:"text",text:C}},Rg=function(C){return{type:"arithmetic",arithmetic:C,quoted:!1}},qp=function(C){return{type:"shell",shell:C,quoted:!1}},Jp=function(C){return{type:"variable",...C,quoted:!1}},xr=function(C){return{type:"glob",pattern:C}},oe=/^[^']/,Eo=Ye(["'"],!0,!1),Dn=function(C){return C.join("")},Fg=/^[^$"]/,Qt=Ye(["$",'"'],!0,!1),Vl=`\\ +;(()=>{var nfe=Object.create;var HS=Object.defineProperty;var sfe=Object.getOwnPropertyDescriptor;var ofe=Object.getOwnPropertyNames;var afe=Object.getPrototypeOf,Afe=Object.prototype.hasOwnProperty;var J=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+r+'" is not supported')});var y=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ht=(r,e)=>{for(var t in e)HS(r,t,{get:e[t],enumerable:!0})},lfe=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ofe(e))!Afe.call(r,n)&&n!==t&&HS(r,n,{get:()=>e[n],enumerable:!(i=sfe(e,n))||i.enumerable});return r};var ne=(r,e,t)=>(t=r!=null?nfe(afe(r)):{},lfe(e||!r||!r.__esModule?HS(t,"default",{value:r,enumerable:!0}):t,r));var ZU=y(($_e,_U)=>{_U.exports=XU;XU.sync=Dfe;var zU=J("fs");function Pfe(r,e){var t=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!t||(t=t.split(";"),t.indexOf("")!==-1))return!0;for(var i=0;i{r1.exports=e1;e1.sync=kfe;var $U=J("fs");function e1(r,e,t){$U.stat(r,function(i,n){t(i,i?!1:t1(n,e))})}function kfe(r,e){return t1($U.statSync(r),e)}function t1(r,e){return r.isFile()&&Rfe(r,e)}function Rfe(r,e){var t=r.mode,i=r.uid,n=r.gid,s=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),o=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),l=parseInt("010",8),c=parseInt("001",8),u=a|l,g=t&c||t&l&&n===o||t&a&&i===s||t&u&&s===0;return g}});var s1=y((rZe,n1)=>{var tZe=J("fs"),RI;process.platform==="win32"||global.TESTING_WINDOWS?RI=ZU():RI=i1();n1.exports=nv;nv.sync=Ffe;function nv(r,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,n){nv(r,e||{},function(s,o){s?n(s):i(o)})})}RI(r,e||{},function(i,n){i&&(i.code==="EACCES"||e&&e.ignoreErrors)&&(i=null,n=!1),t(i,n)})}function Ffe(r,e){try{return RI.sync(r,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}});var g1=y((iZe,u1)=>{var Xg=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",o1=J("path"),Nfe=Xg?";":":",a1=s1(),A1=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),l1=(r,e)=>{let t=e.colon||Nfe,i=r.match(/\//)||Xg&&r.match(/\\/)?[""]:[...Xg?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],n=Xg?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Xg?n.split(t):[""];return Xg&&r.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:i,pathExt:s,pathExtExe:n}},c1=(r,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});let{pathEnv:i,pathExt:n,pathExtExe:s}=l1(r,e),o=[],a=c=>new Promise((u,g)=>{if(c===i.length)return e.all&&o.length?u(o):g(A1(r));let f=i[c],h=/^".*"$/.test(f)?f.slice(1,-1):f,p=o1.join(h,r),m=!h&&/^\.[\\\/]/.test(r)?r.slice(0,2)+p:p;u(l(m,c,0))}),l=(c,u,g)=>new Promise((f,h)=>{if(g===n.length)return f(a(u+1));let p=n[g];a1(c+p,{pathExt:s},(m,w)=>{if(!m&&w)if(e.all)o.push(c+p);else return f(c+p);return f(l(c,u,g+1))})});return t?a(0).then(c=>t(null,c),t):a(0)},Lfe=(r,e)=>{e=e||{};let{pathEnv:t,pathExt:i,pathExtExe:n}=l1(r,e),s=[];for(let o=0;o{"use strict";var f1=(r={})=>{let e=r.env||process.env;return(r.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(i=>i.toUpperCase()==="PATH")||"Path"};sv.exports=f1;sv.exports.default=f1});var m1=y((sZe,C1)=>{"use strict";var p1=J("path"),Tfe=g1(),Ofe=h1();function d1(r,e){let t=r.options.env||process.env,i=process.cwd(),n=r.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(r.options.cwd)}catch{}let o;try{o=Tfe.sync(r.command,{path:t[Ofe({env:t})],pathExt:e?p1.delimiter:void 0})}catch{}finally{s&&process.chdir(i)}return o&&(o=p1.resolve(n?r.options.cwd:"",o)),o}function Mfe(r){return d1(r)||d1(r,!0)}C1.exports=Mfe});var E1=y((oZe,av)=>{"use strict";var ov=/([()\][%!^"`<>&|;, *?])/g;function Kfe(r){return r=r.replace(ov,"^$1"),r}function Ufe(r,e){return r=`${r}`,r=r.replace(/(\\*)"/g,'$1$1\\"'),r=r.replace(/(\\*)$/,"$1$1"),r=`"${r}"`,r=r.replace(ov,"^$1"),e&&(r=r.replace(ov,"^$1")),r}av.exports.command=Kfe;av.exports.argument=Ufe});var y1=y((aZe,I1)=>{"use strict";I1.exports=/^#!(.*)/});var B1=y((AZe,w1)=>{"use strict";var Hfe=y1();w1.exports=(r="")=>{let e=r.match(Hfe);if(!e)return null;let[t,i]=e[0].replace(/#! ?/,"").split(" "),n=t.split("/").pop();return n==="env"?i:i?`${n} ${i}`:n}});var b1=y((lZe,Q1)=>{"use strict";var Av=J("fs"),Gfe=B1();function Yfe(r){let t=Buffer.alloc(150),i;try{i=Av.openSync(r,"r"),Av.readSync(i,t,0,150,0),Av.closeSync(i)}catch{}return Gfe(t.toString())}Q1.exports=Yfe});var P1=y((cZe,x1)=>{"use strict";var jfe=J("path"),S1=m1(),v1=E1(),qfe=b1(),Jfe=process.platform==="win32",Wfe=/\.(?:com|exe)$/i,zfe=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Vfe(r){r.file=S1(r);let e=r.file&&qfe(r.file);return e?(r.args.unshift(r.file),r.command=e,S1(r)):r.file}function Xfe(r){if(!Jfe)return r;let e=Vfe(r),t=!Wfe.test(e);if(r.options.forceShell||t){let i=zfe.test(e);r.command=jfe.normalize(r.command),r.command=v1.command(r.command),r.args=r.args.map(s=>v1.argument(s,i));let n=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${n}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}function _fe(r,e,t){e&&!Array.isArray(e)&&(t=e,e=null),e=e?e.slice(0):[],t=Object.assign({},t);let i={command:r,args:e,options:t,file:void 0,original:{command:r,args:e}};return t.shell?i:Xfe(i)}x1.exports=_fe});var R1=y((uZe,k1)=>{"use strict";var lv=process.platform==="win32";function cv(r,e){return Object.assign(new Error(`${e} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${r.command}`,path:r.command,spawnargs:r.args})}function Zfe(r,e){if(!lv)return;let t=r.emit;r.emit=function(i,n){if(i==="exit"){let s=D1(n,e,"spawn");if(s)return t.call(r,"error",s)}return t.apply(r,arguments)}}function D1(r,e){return lv&&r===1&&!e.file?cv(e.original,"spawn"):null}function $fe(r,e){return lv&&r===1&&!e.file?cv(e.original,"spawnSync"):null}k1.exports={hookChildProcess:Zfe,verifyENOENT:D1,verifyENOENTSync:$fe,notFoundError:cv}});var fv=y((gZe,_g)=>{"use strict";var F1=J("child_process"),uv=P1(),gv=R1();function N1(r,e,t){let i=uv(r,e,t),n=F1.spawn(i.command,i.args,i.options);return gv.hookChildProcess(n,i),n}function ehe(r,e,t){let i=uv(r,e,t),n=F1.spawnSync(i.command,i.args,i.options);return n.error=n.error||gv.verifyENOENTSync(n.status,i),n}_g.exports=N1;_g.exports.spawn=N1;_g.exports.sync=ehe;_g.exports._parse=uv;_g.exports._enoent=gv});var T1=y((fZe,L1)=>{"use strict";function the(r,e){function t(){this.constructor=r}t.prototype=e.prototype,r.prototype=new t}function cc(r,e,t,i){this.message=r,this.expected=e,this.found=t,this.location=i,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,cc)}the(cc,Error);cc.buildMessage=function(r,e){var t={literal:function(c){return'"'+n(c.text)+'"'},class:function(c){var u="",g;for(g=0;g0){for(g=1,f=1;g>",te=de(">>",!1),me=">&",tt=de(">&",!1),Rt=">",It=de(">",!1),Kr="<<<",oi=de("<<<",!1),pi="<&",pr=de("<&",!1),di="<",ai=de("<",!1),Os=function(C){return{type:"argument",segments:[].concat(...C)}},dr=function(C){return C},Bi="$'",_n=de("$'",!1),ga="'",CA=de("'",!1),Dg=function(C){return[{type:"text",text:C}]},Zn='""',mA=de('""',!1),fa=function(){return{type:"text",text:""}},jp='"',EA=de('"',!1),IA=function(C){return C},wr=function(C){return{type:"arithmetic",arithmetic:C,quoted:!0}},zl=function(C){return{type:"shell",shell:C,quoted:!0}},kg=function(C){return{type:"variable",...C,quoted:!0}},mo=function(C){return{type:"text",text:C}},Rg=function(C){return{type:"arithmetic",arithmetic:C,quoted:!1}},qp=function(C){return{type:"shell",shell:C,quoted:!1}},Jp=function(C){return{type:"variable",...C,quoted:!1}},xr=function(C){return{type:"glob",pattern:C}},oe=/^[^']/,Eo=Ye(["'"],!0,!1),Dn=function(C){return C.join("")},Fg=/^[^$"]/,Qt=Ye(["$",'"'],!0,!1),Vl=`\\ `,kn=de(`\\ `,!1),$n=function(){return""},es="\\",ut=de("\\",!1),Io=/^[\\$"`]/,at=Ye(["\\","$",'"',"`"],!1,!1),ln=function(C){return C},S="\\a",Tt=de("\\a",!1),Ng=function(){return"a"},Xl="\\b",Wp=de("\\b",!1),zp=function(){return"\b"},Vp=/^[Ee]/,Xp=Ye(["E","e"],!1,!1),_p=function(){return"\x1B"},G="\\f",yt=de("\\f",!1),yA=function(){return"\f"},Wi="\\n",_l=de("\\n",!1),We=function(){return` `},ha="\\r",Lg=de("\\r",!1),oI=function(){return"\r"},Zp="\\t",aI=de("\\t",!1),ar=function(){return" "},Rn="\\v",Zl=de("\\v",!1),$p=function(){return"\v"},Ms=/^[\\'"?]/,pa=Ye(["\\","'",'"',"?"],!1,!1),cn=function(C){return String.fromCharCode(parseInt(C,16))},De="\\x",Tg=de("\\x",!1),$l="\\u",Ks=de("\\u",!1),ec="\\U",wA=de("\\U",!1),Og=function(C){return String.fromCodePoint(parseInt(C,16))},Mg=/^[0-7]/,da=Ye([["0","7"]],!1,!1),Ca=/^[0-9a-fA-f]/,$e=Ye([["0","9"],["a","f"],["A","f"]],!1,!1),yo=rt(),BA="-",tc=de("-",!1),Us="+",rc=de("+",!1),AI=".",ed=de(".",!1),Kg=function(C,b,N){return{type:"number",value:(C==="-"?-1:1)*parseFloat(b.join("")+"."+N.join(""))}},td=function(C,b){return{type:"number",value:(C==="-"?-1:1)*parseInt(b.join(""))}},lI=function(C){return{type:"variable",...C}},ic=function(C){return{type:"variable",name:C}},cI=function(C){return C},Ug="*",QA=de("*",!1),Rr="/",uI=de("/",!1),Hs=function(C,b,N){return{type:b==="*"?"multiplication":"division",right:N}},Gs=function(C,b){return b.reduce((N,U)=>({left:N,...U}),C)},Hg=function(C,b,N){return{type:b==="+"?"addition":"subtraction",right:N}},bA="$((",R=de("$((",!1),q="))",pe=de("))",!1),Ne=function(C){return C},xe="$(",qe=de("$(",!1),dt=function(C){return C},Ft="${",Fn=de("${",!1),QS=":-",tU=de(":-",!1),rU=function(C,b){return{name:C,defaultValue:b}},bS=":-}",iU=de(":-}",!1),nU=function(C){return{name:C,defaultValue:[]}},SS=":+",sU=de(":+",!1),oU=function(C,b){return{name:C,alternativeValue:b}},vS=":+}",aU=de(":+}",!1),AU=function(C){return{name:C,alternativeValue:[]}},xS=function(C){return{name:C}},lU="$",cU=de("$",!1),uU=function(C){return e.isGlobPattern(C)},gU=function(C){return C},PS=/^[a-zA-Z0-9_]/,DS=Ye([["a","z"],["A","Z"],["0","9"],"_"],!1,!1),kS=function(){return O()},RS=/^[$@*?#a-zA-Z0-9_\-]/,FS=Ye(["$","@","*","?","#",["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),fU=/^[(){}<>$|&; \t"']/,Gg=Ye(["(",")","{","}","<",">","$","|","&",";"," "," ",'"',"'"],!1,!1),NS=/^[<>&; \t"']/,LS=Ye(["<",">","&",";"," "," ",'"',"'"],!1,!1),gI=/^[ \t]/,fI=Ye([" "," "],!1,!1),Q=0,Re=0,SA=[{line:1,column:1}],d=0,E=[],I=0,k;if("startRule"in e){if(!(e.startRule in i))throw new Error(`Can't start parsing from rule "`+e.startRule+'".');n=i[e.startRule]}function O(){return r.substring(Re,Q)}function X(){return Et(Re,Q)}function ee(C,b){throw b=b!==void 0?b:Et(Re,Q),Fi([At(C)],r.substring(Re,Q),b)}function ye(C,b){throw b=b!==void 0?b:Et(Re,Q),Nn(C,b)}function de(C,b){return{type:"literal",text:C,ignoreCase:b}}function Ye(C,b,N){return{type:"class",parts:C,inverted:b,ignoreCase:N}}function rt(){return{type:"any"}}function wt(){return{type:"end"}}function At(C){return{type:"other",description:C}}function et(C){var b=SA[C],N;if(b)return b;for(N=C-1;!SA[N];)N--;for(b=SA[N],b={line:b.line,column:b.column};Nd&&(d=Q,E=[]),E.push(C))}function Nn(C,b){return new cc(C,null,null,b)}function Fi(C,b,N){return new cc(cc.buildMessage(C,b),C,b,N)}function vA(){var C,b;return C=Q,b=Ur(),b===t&&(b=null),b!==t&&(Re=C,b=s(b)),C=b,C}function Ur(){var C,b,N,U,ce;if(C=Q,b=Hr(),b!==t){for(N=[],U=Me();U!==t;)N.push(U),U=Me();N!==t?(U=ma(),U!==t?(ce=ts(),ce===t&&(ce=null),ce!==t?(Re=C,b=o(b,U,ce),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t)}else Q=C,C=t;if(C===t)if(C=Q,b=Hr(),b!==t){for(N=[],U=Me();U!==t;)N.push(U),U=Me();N!==t?(U=ma(),U===t&&(U=null),U!==t?(Re=C,b=a(b,U),C=b):(Q=C,C=t)):(Q=C,C=t)}else Q=C,C=t;return C}function ts(){var C,b,N,U,ce;for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t)if(N=Ur(),N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();U!==t?(Re=C,b=l(N),C=b):(Q=C,C=t)}else Q=C,C=t;else Q=C,C=t;return C}function ma(){var C;return r.charCodeAt(Q)===59?(C=c,Q++):(C=t,I===0&&Be(u)),C===t&&(r.charCodeAt(Q)===38?(C=g,Q++):(C=t,I===0&&Be(f))),C}function Hr(){var C,b,N;return C=Q,b=hU(),b!==t?(N=Hge(),N===t&&(N=null),N!==t?(Re=C,b=h(b,N),C=b):(Q=C,C=t)):(Q=C,C=t),C}function Hge(){var C,b,N,U,ce,be,ft;for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t)if(N=Gge(),N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();if(U!==t)if(ce=Hr(),ce!==t){for(be=[],ft=Me();ft!==t;)be.push(ft),ft=Me();be!==t?(Re=C,b=p(N,ce),C=b):(Q=C,C=t)}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t;else Q=C,C=t;return C}function Gge(){var C;return r.substr(Q,2)===m?(C=m,Q+=2):(C=t,I===0&&Be(w)),C===t&&(r.substr(Q,2)===B?(C=B,Q+=2):(C=t,I===0&&Be(v))),C}function hU(){var C,b,N;return C=Q,b=qge(),b!==t?(N=Yge(),N===t&&(N=null),N!==t?(Re=C,b=D(b,N),C=b):(Q=C,C=t)):(Q=C,C=t),C}function Yge(){var C,b,N,U,ce,be,ft;for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t)if(N=jge(),N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();if(U!==t)if(ce=hU(),ce!==t){for(be=[],ft=Me();ft!==t;)be.push(ft),ft=Me();be!==t?(Re=C,b=F(N,ce),C=b):(Q=C,C=t)}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t;else Q=C,C=t;return C}function jge(){var C;return r.substr(Q,2)===H?(C=H,Q+=2):(C=t,I===0&&Be(j)),C===t&&(r.charCodeAt(Q)===124?(C=$,Q++):(C=t,I===0&&Be(z))),C}function hI(){var C,b,N,U,ce,be;if(C=Q,b=SU(),b!==t)if(r.charCodeAt(Q)===61?(N=W,Q++):(N=t,I===0&&Be(Z)),N!==t)if(U=CU(),U!==t){for(ce=[],be=Me();be!==t;)ce.push(be),be=Me();ce!==t?(Re=C,b=A(b,U),C=b):(Q=C,C=t)}else Q=C,C=t;else Q=C,C=t;else Q=C,C=t;if(C===t)if(C=Q,b=SU(),b!==t)if(r.charCodeAt(Q)===61?(N=W,Q++):(N=t,I===0&&Be(Z)),N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();U!==t?(Re=C,b=ae(b),C=b):(Q=C,C=t)}else Q=C,C=t;else Q=C,C=t;return C}function qge(){var C,b,N,U,ce,be,ft,Bt,Vr,Ci,rs;for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t)if(r.charCodeAt(Q)===40?(N=ue,Q++):(N=t,I===0&&Be(_)),N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();if(U!==t)if(ce=Ur(),ce!==t){for(be=[],ft=Me();ft!==t;)be.push(ft),ft=Me();if(be!==t)if(r.charCodeAt(Q)===41?(ft=T,Q++):(ft=t,I===0&&Be(L)),ft!==t){for(Bt=[],Vr=Me();Vr!==t;)Bt.push(Vr),Vr=Me();if(Bt!==t){for(Vr=[],Ci=rd();Ci!==t;)Vr.push(Ci),Ci=rd();if(Vr!==t){for(Ci=[],rs=Me();rs!==t;)Ci.push(rs),rs=Me();Ci!==t?(Re=C,b=ge(ce,Vr),C=b):(Q=C,C=t)}else Q=C,C=t}else Q=C,C=t}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t;else Q=C,C=t;if(C===t){for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t)if(r.charCodeAt(Q)===123?(N=we,Q++):(N=t,I===0&&Be(Le)),N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();if(U!==t)if(ce=Ur(),ce!==t){for(be=[],ft=Me();ft!==t;)be.push(ft),ft=Me();if(be!==t)if(r.charCodeAt(Q)===125?(ft=Pe,Q++):(ft=t,I===0&&Be(Te)),ft!==t){for(Bt=[],Vr=Me();Vr!==t;)Bt.push(Vr),Vr=Me();if(Bt!==t){for(Vr=[],Ci=rd();Ci!==t;)Vr.push(Ci),Ci=rd();if(Vr!==t){for(Ci=[],rs=Me();rs!==t;)Ci.push(rs),rs=Me();Ci!==t?(Re=C,b=se(ce,Vr),C=b):(Q=C,C=t)}else Q=C,C=t}else Q=C,C=t}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t;else Q=C,C=t;if(C===t){for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t){for(N=[],U=hI();U!==t;)N.push(U),U=hI();if(N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();if(U!==t){if(ce=[],be=dU(),be!==t)for(;be!==t;)ce.push(be),be=dU();else ce=t;if(ce!==t){for(be=[],ft=Me();ft!==t;)be.push(ft),ft=Me();be!==t?(Re=C,b=Ae(N,ce),C=b):(Q=C,C=t)}else Q=C,C=t}else Q=C,C=t}else Q=C,C=t}else Q=C,C=t;if(C===t){for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t){if(N=[],U=hI(),U!==t)for(;U!==t;)N.push(U),U=hI();else N=t;if(N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();U!==t?(Re=C,b=Qe(N),C=b):(Q=C,C=t)}else Q=C,C=t}else Q=C,C=t}}}return C}function pU(){var C,b,N,U,ce;for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t){if(N=[],U=pI(),U!==t)for(;U!==t;)N.push(U),U=pI();else N=t;if(N!==t){for(U=[],ce=Me();ce!==t;)U.push(ce),ce=Me();U!==t?(Re=C,b=fe(N),C=b):(Q=C,C=t)}else Q=C,C=t}else Q=C,C=t;return C}function dU(){var C,b,N;for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();if(b!==t?(N=rd(),N!==t?(Re=C,b=le(N),C=b):(Q=C,C=t)):(Q=C,C=t),C===t){for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();b!==t?(N=pI(),N!==t?(Re=C,b=le(N),C=b):(Q=C,C=t)):(Q=C,C=t)}return C}function rd(){var C,b,N,U,ce;for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();return b!==t?(Ge.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(ie)),N===t&&(N=null),N!==t?(U=Jge(),U!==t?(ce=pI(),ce!==t?(Re=C,b=Y(N,U,ce),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C}function Jge(){var C;return r.substr(Q,2)===he?(C=he,Q+=2):(C=t,I===0&&Be(te)),C===t&&(r.substr(Q,2)===me?(C=me,Q+=2):(C=t,I===0&&Be(tt)),C===t&&(r.charCodeAt(Q)===62?(C=Rt,Q++):(C=t,I===0&&Be(It)),C===t&&(r.substr(Q,3)===Kr?(C=Kr,Q+=3):(C=t,I===0&&Be(oi)),C===t&&(r.substr(Q,2)===pi?(C=pi,Q+=2):(C=t,I===0&&Be(pr)),C===t&&(r.charCodeAt(Q)===60?(C=di,Q++):(C=t,I===0&&Be(ai))))))),C}function pI(){var C,b,N;for(C=Q,b=[],N=Me();N!==t;)b.push(N),N=Me();return b!==t?(N=CU(),N!==t?(Re=C,b=le(N),C=b):(Q=C,C=t)):(Q=C,C=t),C}function CU(){var C,b,N;if(C=Q,b=[],N=mU(),N!==t)for(;N!==t;)b.push(N),N=mU();else b=t;return b!==t&&(Re=C,b=Os(b)),C=b,C}function mU(){var C,b;return C=Q,b=Wge(),b!==t&&(Re=C,b=dr(b)),C=b,C===t&&(C=Q,b=zge(),b!==t&&(Re=C,b=dr(b)),C=b,C===t&&(C=Q,b=Vge(),b!==t&&(Re=C,b=dr(b)),C=b,C===t&&(C=Q,b=Xge(),b!==t&&(Re=C,b=dr(b)),C=b))),C}function Wge(){var C,b,N,U;return C=Q,r.substr(Q,2)===Bi?(b=Bi,Q+=2):(b=t,I===0&&Be(_n)),b!==t?(N=$ge(),N!==t?(r.charCodeAt(Q)===39?(U=ga,Q++):(U=t,I===0&&Be(CA)),U!==t?(Re=C,b=Dg(N),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C}function zge(){var C,b,N,U;return C=Q,r.charCodeAt(Q)===39?(b=ga,Q++):(b=t,I===0&&Be(CA)),b!==t?(N=_ge(),N!==t?(r.charCodeAt(Q)===39?(U=ga,Q++):(U=t,I===0&&Be(CA)),U!==t?(Re=C,b=Dg(N),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C}function Vge(){var C,b,N,U;if(C=Q,r.substr(Q,2)===Zn?(b=Zn,Q+=2):(b=t,I===0&&Be(mA)),b!==t&&(Re=C,b=fa()),C=b,C===t)if(C=Q,r.charCodeAt(Q)===34?(b=jp,Q++):(b=t,I===0&&Be(EA)),b!==t){for(N=[],U=EU();U!==t;)N.push(U),U=EU();N!==t?(r.charCodeAt(Q)===34?(U=jp,Q++):(U=t,I===0&&Be(EA)),U!==t?(Re=C,b=IA(N),C=b):(Q=C,C=t)):(Q=C,C=t)}else Q=C,C=t;return C}function Xge(){var C,b,N;if(C=Q,b=[],N=IU(),N!==t)for(;N!==t;)b.push(N),N=IU();else b=t;return b!==t&&(Re=C,b=IA(b)),C=b,C}function EU(){var C,b;return C=Q,b=QU(),b!==t&&(Re=C,b=wr(b)),C=b,C===t&&(C=Q,b=bU(),b!==t&&(Re=C,b=zl(b)),C=b,C===t&&(C=Q,b=KS(),b!==t&&(Re=C,b=kg(b)),C=b,C===t&&(C=Q,b=Zge(),b!==t&&(Re=C,b=mo(b)),C=b))),C}function IU(){var C,b;return C=Q,b=QU(),b!==t&&(Re=C,b=Rg(b)),C=b,C===t&&(C=Q,b=bU(),b!==t&&(Re=C,b=qp(b)),C=b,C===t&&(C=Q,b=KS(),b!==t&&(Re=C,b=Jp(b)),C=b,C===t&&(C=Q,b=rfe(),b!==t&&(Re=C,b=xr(b)),C=b,C===t&&(C=Q,b=tfe(),b!==t&&(Re=C,b=mo(b)),C=b)))),C}function _ge(){var C,b,N;for(C=Q,b=[],oe.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(Eo));N!==t;)b.push(N),oe.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(Eo));return b!==t&&(Re=C,b=Dn(b)),C=b,C}function Zge(){var C,b,N;if(C=Q,b=[],N=yU(),N===t&&(Fg.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(Qt))),N!==t)for(;N!==t;)b.push(N),N=yU(),N===t&&(Fg.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(Qt)));else b=t;return b!==t&&(Re=C,b=Dn(b)),C=b,C}function yU(){var C,b,N;return C=Q,r.substr(Q,2)===Vl?(b=Vl,Q+=2):(b=t,I===0&&Be(kn)),b!==t&&(Re=C,b=$n()),C=b,C===t&&(C=Q,r.charCodeAt(Q)===92?(b=es,Q++):(b=t,I===0&&Be(ut)),b!==t?(Io.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(at)),N!==t?(Re=C,b=ln(N),C=b):(Q=C,C=t)):(Q=C,C=t)),C}function $ge(){var C,b,N;for(C=Q,b=[],N=wU(),N===t&&(oe.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(Eo)));N!==t;)b.push(N),N=wU(),N===t&&(oe.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(Eo)));return b!==t&&(Re=C,b=Dn(b)),C=b,C}function wU(){var C,b,N;return C=Q,r.substr(Q,2)===S?(b=S,Q+=2):(b=t,I===0&&Be(Tt)),b!==t&&(Re=C,b=Ng()),C=b,C===t&&(C=Q,r.substr(Q,2)===Xl?(b=Xl,Q+=2):(b=t,I===0&&Be(Wp)),b!==t&&(Re=C,b=zp()),C=b,C===t&&(C=Q,r.charCodeAt(Q)===92?(b=es,Q++):(b=t,I===0&&Be(ut)),b!==t?(Vp.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(Xp)),N!==t?(Re=C,b=_p(),C=b):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.substr(Q,2)===G?(b=G,Q+=2):(b=t,I===0&&Be(yt)),b!==t&&(Re=C,b=yA()),C=b,C===t&&(C=Q,r.substr(Q,2)===Wi?(b=Wi,Q+=2):(b=t,I===0&&Be(_l)),b!==t&&(Re=C,b=We()),C=b,C===t&&(C=Q,r.substr(Q,2)===ha?(b=ha,Q+=2):(b=t,I===0&&Be(Lg)),b!==t&&(Re=C,b=oI()),C=b,C===t&&(C=Q,r.substr(Q,2)===Zp?(b=Zp,Q+=2):(b=t,I===0&&Be(aI)),b!==t&&(Re=C,b=ar()),C=b,C===t&&(C=Q,r.substr(Q,2)===Rn?(b=Rn,Q+=2):(b=t,I===0&&Be(Zl)),b!==t&&(Re=C,b=$p()),C=b,C===t&&(C=Q,r.charCodeAt(Q)===92?(b=es,Q++):(b=t,I===0&&Be(ut)),b!==t?(Ms.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(pa)),N!==t?(Re=C,b=ln(N),C=b):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=efe()))))))))),C}function efe(){var C,b,N,U,ce,be,ft,Bt,Vr,Ci,rs,US;return C=Q,r.charCodeAt(Q)===92?(b=es,Q++):(b=t,I===0&&Be(ut)),b!==t?(N=TS(),N!==t?(Re=C,b=cn(N),C=b):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.substr(Q,2)===De?(b=De,Q+=2):(b=t,I===0&&Be(Tg)),b!==t?(N=Q,U=Q,ce=TS(),ce!==t?(be=Ln(),be!==t?(ce=[ce,be],U=ce):(Q=U,U=t)):(Q=U,U=t),U===t&&(U=TS()),U!==t?N=r.substring(N,Q):N=U,N!==t?(Re=C,b=cn(N),C=b):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.substr(Q,2)===$l?(b=$l,Q+=2):(b=t,I===0&&Be(Ks)),b!==t?(N=Q,U=Q,ce=Ln(),ce!==t?(be=Ln(),be!==t?(ft=Ln(),ft!==t?(Bt=Ln(),Bt!==t?(ce=[ce,be,ft,Bt],U=ce):(Q=U,U=t)):(Q=U,U=t)):(Q=U,U=t)):(Q=U,U=t),U!==t?N=r.substring(N,Q):N=U,N!==t?(Re=C,b=cn(N),C=b):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.substr(Q,2)===ec?(b=ec,Q+=2):(b=t,I===0&&Be(wA)),b!==t?(N=Q,U=Q,ce=Ln(),ce!==t?(be=Ln(),be!==t?(ft=Ln(),ft!==t?(Bt=Ln(),Bt!==t?(Vr=Ln(),Vr!==t?(Ci=Ln(),Ci!==t?(rs=Ln(),rs!==t?(US=Ln(),US!==t?(ce=[ce,be,ft,Bt,Vr,Ci,rs,US],U=ce):(Q=U,U=t)):(Q=U,U=t)):(Q=U,U=t)):(Q=U,U=t)):(Q=U,U=t)):(Q=U,U=t)):(Q=U,U=t)):(Q=U,U=t),U!==t?N=r.substring(N,Q):N=U,N!==t?(Re=C,b=Og(N),C=b):(Q=C,C=t)):(Q=C,C=t)))),C}function TS(){var C;return Mg.test(r.charAt(Q))?(C=r.charAt(Q),Q++):(C=t,I===0&&Be(da)),C}function Ln(){var C;return Ca.test(r.charAt(Q))?(C=r.charAt(Q),Q++):(C=t,I===0&&Be($e)),C}function tfe(){var C,b,N,U,ce;if(C=Q,b=[],N=Q,r.charCodeAt(Q)===92?(U=es,Q++):(U=t,I===0&&Be(ut)),U!==t?(r.length>Q?(ce=r.charAt(Q),Q++):(ce=t,I===0&&Be(yo)),ce!==t?(Re=N,U=ln(ce),N=U):(Q=N,N=t)):(Q=N,N=t),N===t&&(N=Q,U=Q,I++,ce=vU(),I--,ce===t?U=void 0:(Q=U,U=t),U!==t?(r.length>Q?(ce=r.charAt(Q),Q++):(ce=t,I===0&&Be(yo)),ce!==t?(Re=N,U=ln(ce),N=U):(Q=N,N=t)):(Q=N,N=t)),N!==t)for(;N!==t;)b.push(N),N=Q,r.charCodeAt(Q)===92?(U=es,Q++):(U=t,I===0&&Be(ut)),U!==t?(r.length>Q?(ce=r.charAt(Q),Q++):(ce=t,I===0&&Be(yo)),ce!==t?(Re=N,U=ln(ce),N=U):(Q=N,N=t)):(Q=N,N=t),N===t&&(N=Q,U=Q,I++,ce=vU(),I--,ce===t?U=void 0:(Q=U,U=t),U!==t?(r.length>Q?(ce=r.charAt(Q),Q++):(ce=t,I===0&&Be(yo)),ce!==t?(Re=N,U=ln(ce),N=U):(Q=N,N=t)):(Q=N,N=t));else b=t;return b!==t&&(Re=C,b=Dn(b)),C=b,C}function OS(){var C,b,N,U,ce,be;if(C=Q,r.charCodeAt(Q)===45?(b=BA,Q++):(b=t,I===0&&Be(tc)),b===t&&(r.charCodeAt(Q)===43?(b=Us,Q++):(b=t,I===0&&Be(rc))),b===t&&(b=null),b!==t){if(N=[],Ge.test(r.charAt(Q))?(U=r.charAt(Q),Q++):(U=t,I===0&&Be(ie)),U!==t)for(;U!==t;)N.push(U),Ge.test(r.charAt(Q))?(U=r.charAt(Q),Q++):(U=t,I===0&&Be(ie));else N=t;if(N!==t)if(r.charCodeAt(Q)===46?(U=AI,Q++):(U=t,I===0&&Be(ed)),U!==t){if(ce=[],Ge.test(r.charAt(Q))?(be=r.charAt(Q),Q++):(be=t,I===0&&Be(ie)),be!==t)for(;be!==t;)ce.push(be),Ge.test(r.charAt(Q))?(be=r.charAt(Q),Q++):(be=t,I===0&&Be(ie));else ce=t;ce!==t?(Re=C,b=Kg(b,N,ce),C=b):(Q=C,C=t)}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t;if(C===t){if(C=Q,r.charCodeAt(Q)===45?(b=BA,Q++):(b=t,I===0&&Be(tc)),b===t&&(r.charCodeAt(Q)===43?(b=Us,Q++):(b=t,I===0&&Be(rc))),b===t&&(b=null),b!==t){if(N=[],Ge.test(r.charAt(Q))?(U=r.charAt(Q),Q++):(U=t,I===0&&Be(ie)),U!==t)for(;U!==t;)N.push(U),Ge.test(r.charAt(Q))?(U=r.charAt(Q),Q++):(U=t,I===0&&Be(ie));else N=t;N!==t?(Re=C,b=td(b,N),C=b):(Q=C,C=t)}else Q=C,C=t;if(C===t&&(C=Q,b=KS(),b!==t&&(Re=C,b=lI(b)),C=b,C===t&&(C=Q,b=nc(),b!==t&&(Re=C,b=ic(b)),C=b,C===t)))if(C=Q,r.charCodeAt(Q)===40?(b=ue,Q++):(b=t,I===0&&Be(_)),b!==t){for(N=[],U=Me();U!==t;)N.push(U),U=Me();if(N!==t)if(U=BU(),U!==t){for(ce=[],be=Me();be!==t;)ce.push(be),be=Me();ce!==t?(r.charCodeAt(Q)===41?(be=T,Q++):(be=t,I===0&&Be(L)),be!==t?(Re=C,b=cI(U),C=b):(Q=C,C=t)):(Q=C,C=t)}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t}return C}function MS(){var C,b,N,U,ce,be,ft,Bt;if(C=Q,b=OS(),b!==t){for(N=[],U=Q,ce=[],be=Me();be!==t;)ce.push(be),be=Me();if(ce!==t)if(r.charCodeAt(Q)===42?(be=Ug,Q++):(be=t,I===0&&Be(QA)),be===t&&(r.charCodeAt(Q)===47?(be=Rr,Q++):(be=t,I===0&&Be(uI))),be!==t){for(ft=[],Bt=Me();Bt!==t;)ft.push(Bt),Bt=Me();ft!==t?(Bt=OS(),Bt!==t?(Re=U,ce=Hs(b,be,Bt),U=ce):(Q=U,U=t)):(Q=U,U=t)}else Q=U,U=t;else Q=U,U=t;for(;U!==t;){for(N.push(U),U=Q,ce=[],be=Me();be!==t;)ce.push(be),be=Me();if(ce!==t)if(r.charCodeAt(Q)===42?(be=Ug,Q++):(be=t,I===0&&Be(QA)),be===t&&(r.charCodeAt(Q)===47?(be=Rr,Q++):(be=t,I===0&&Be(uI))),be!==t){for(ft=[],Bt=Me();Bt!==t;)ft.push(Bt),Bt=Me();ft!==t?(Bt=OS(),Bt!==t?(Re=U,ce=Hs(b,be,Bt),U=ce):(Q=U,U=t)):(Q=U,U=t)}else Q=U,U=t;else Q=U,U=t}N!==t?(Re=C,b=Gs(b,N),C=b):(Q=C,C=t)}else Q=C,C=t;return C}function BU(){var C,b,N,U,ce,be,ft,Bt;if(C=Q,b=MS(),b!==t){for(N=[],U=Q,ce=[],be=Me();be!==t;)ce.push(be),be=Me();if(ce!==t)if(r.charCodeAt(Q)===43?(be=Us,Q++):(be=t,I===0&&Be(rc)),be===t&&(r.charCodeAt(Q)===45?(be=BA,Q++):(be=t,I===0&&Be(tc))),be!==t){for(ft=[],Bt=Me();Bt!==t;)ft.push(Bt),Bt=Me();ft!==t?(Bt=MS(),Bt!==t?(Re=U,ce=Hg(b,be,Bt),U=ce):(Q=U,U=t)):(Q=U,U=t)}else Q=U,U=t;else Q=U,U=t;for(;U!==t;){for(N.push(U),U=Q,ce=[],be=Me();be!==t;)ce.push(be),be=Me();if(ce!==t)if(r.charCodeAt(Q)===43?(be=Us,Q++):(be=t,I===0&&Be(rc)),be===t&&(r.charCodeAt(Q)===45?(be=BA,Q++):(be=t,I===0&&Be(tc))),be!==t){for(ft=[],Bt=Me();Bt!==t;)ft.push(Bt),Bt=Me();ft!==t?(Bt=MS(),Bt!==t?(Re=U,ce=Hg(b,be,Bt),U=ce):(Q=U,U=t)):(Q=U,U=t)}else Q=U,U=t;else Q=U,U=t}N!==t?(Re=C,b=Gs(b,N),C=b):(Q=C,C=t)}else Q=C,C=t;return C}function QU(){var C,b,N,U,ce,be;if(C=Q,r.substr(Q,3)===bA?(b=bA,Q+=3):(b=t,I===0&&Be(R)),b!==t){for(N=[],U=Me();U!==t;)N.push(U),U=Me();if(N!==t)if(U=BU(),U!==t){for(ce=[],be=Me();be!==t;)ce.push(be),be=Me();ce!==t?(r.substr(Q,2)===q?(be=q,Q+=2):(be=t,I===0&&Be(pe)),be!==t?(Re=C,b=Ne(U),C=b):(Q=C,C=t)):(Q=C,C=t)}else Q=C,C=t;else Q=C,C=t}else Q=C,C=t;return C}function bU(){var C,b,N,U;return C=Q,r.substr(Q,2)===xe?(b=xe,Q+=2):(b=t,I===0&&Be(qe)),b!==t?(N=Ur(),N!==t?(r.charCodeAt(Q)===41?(U=T,Q++):(U=t,I===0&&Be(L)),U!==t?(Re=C,b=dt(N),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C}function KS(){var C,b,N,U,ce,be;return C=Q,r.substr(Q,2)===Ft?(b=Ft,Q+=2):(b=t,I===0&&Be(Fn)),b!==t?(N=nc(),N!==t?(r.substr(Q,2)===QS?(U=QS,Q+=2):(U=t,I===0&&Be(tU)),U!==t?(ce=pU(),ce!==t?(r.charCodeAt(Q)===125?(be=Pe,Q++):(be=t,I===0&&Be(Te)),be!==t?(Re=C,b=rU(N,ce),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.substr(Q,2)===Ft?(b=Ft,Q+=2):(b=t,I===0&&Be(Fn)),b!==t?(N=nc(),N!==t?(r.substr(Q,3)===bS?(U=bS,Q+=3):(U=t,I===0&&Be(iU)),U!==t?(Re=C,b=nU(N),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.substr(Q,2)===Ft?(b=Ft,Q+=2):(b=t,I===0&&Be(Fn)),b!==t?(N=nc(),N!==t?(r.substr(Q,2)===SS?(U=SS,Q+=2):(U=t,I===0&&Be(sU)),U!==t?(ce=pU(),ce!==t?(r.charCodeAt(Q)===125?(be=Pe,Q++):(be=t,I===0&&Be(Te)),be!==t?(Re=C,b=oU(N,ce),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.substr(Q,2)===Ft?(b=Ft,Q+=2):(b=t,I===0&&Be(Fn)),b!==t?(N=nc(),N!==t?(r.substr(Q,3)===vS?(U=vS,Q+=3):(U=t,I===0&&Be(aU)),U!==t?(Re=C,b=AU(N),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.substr(Q,2)===Ft?(b=Ft,Q+=2):(b=t,I===0&&Be(Fn)),b!==t?(N=nc(),N!==t?(r.charCodeAt(Q)===125?(U=Pe,Q++):(U=t,I===0&&Be(Te)),U!==t?(Re=C,b=xS(N),C=b):(Q=C,C=t)):(Q=C,C=t)):(Q=C,C=t),C===t&&(C=Q,r.charCodeAt(Q)===36?(b=lU,Q++):(b=t,I===0&&Be(cU)),b!==t?(N=nc(),N!==t?(Re=C,b=xS(N),C=b):(Q=C,C=t)):(Q=C,C=t)))))),C}function rfe(){var C,b,N;return C=Q,b=ife(),b!==t?(Re=Q,N=uU(b),N?N=void 0:N=t,N!==t?(Re=C,b=gU(b),C=b):(Q=C,C=t)):(Q=C,C=t),C}function ife(){var C,b,N,U,ce;if(C=Q,b=[],N=Q,U=Q,I++,ce=xU(),I--,ce===t?U=void 0:(Q=U,U=t),U!==t?(r.length>Q?(ce=r.charAt(Q),Q++):(ce=t,I===0&&Be(yo)),ce!==t?(Re=N,U=ln(ce),N=U):(Q=N,N=t)):(Q=N,N=t),N!==t)for(;N!==t;)b.push(N),N=Q,U=Q,I++,ce=xU(),I--,ce===t?U=void 0:(Q=U,U=t),U!==t?(r.length>Q?(ce=r.charAt(Q),Q++):(ce=t,I===0&&Be(yo)),ce!==t?(Re=N,U=ln(ce),N=U):(Q=N,N=t)):(Q=N,N=t);else b=t;return b!==t&&(Re=C,b=Dn(b)),C=b,C}function SU(){var C,b,N;if(C=Q,b=[],PS.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(DS)),N!==t)for(;N!==t;)b.push(N),PS.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(DS));else b=t;return b!==t&&(Re=C,b=kS()),C=b,C}function nc(){var C,b,N;if(C=Q,b=[],RS.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(FS)),N!==t)for(;N!==t;)b.push(N),RS.test(r.charAt(Q))?(N=r.charAt(Q),Q++):(N=t,I===0&&Be(FS));else b=t;return b!==t&&(Re=C,b=kS()),C=b,C}function vU(){var C;return fU.test(r.charAt(Q))?(C=r.charAt(Q),Q++):(C=t,I===0&&Be(Gg)),C}function xU(){var C;return NS.test(r.charAt(Q))?(C=r.charAt(Q),Q++):(C=t,I===0&&Be(LS)),C}function Me(){var C,b;if(C=[],gI.test(r.charAt(Q))?(b=r.charAt(Q),Q++):(b=t,I===0&&Be(fI)),b!==t)for(;b!==t;)C.push(b),gI.test(r.charAt(Q))?(b=r.charAt(Q),Q++):(b=t,I===0&&Be(fI));else C=t;return C}if(k=n(),k!==t&&Q===r.length)return k;throw k!==t&&Q{"use strict";function ihe(r,e){function t(){this.constructor=r}t.prototype=e.prototype,r.prototype=new t}function gc(r,e,t,i){this.message=r,this.expected=e,this.found=t,this.location=i,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,gc)}ihe(gc,Error);gc.buildMessage=function(r,e){var t={literal:function(c){return'"'+n(c.text)+'"'},class:function(c){var u="",g;for(g=0;g0){for(g=1,f=1;gH&&(H=v,j=[]),j.push(ie))}function Te(ie,Y){return new gc(ie,null,null,Y)}function se(ie,Y,he){return new gc(gc.buildMessage(ie,Y),ie,Y,he)}function Ae(){var ie,Y,he,te;return ie=v,Y=Qe(),Y!==t?(r.charCodeAt(v)===47?(he=s,v++):(he=t,$===0&&Pe(o)),he!==t?(te=Qe(),te!==t?(D=ie,Y=a(Y,te),ie=Y):(v=ie,ie=t)):(v=ie,ie=t)):(v=ie,ie=t),ie===t&&(ie=v,Y=Qe(),Y!==t&&(D=ie,Y=l(Y)),ie=Y),ie}function Qe(){var ie,Y,he,te;return ie=v,Y=fe(),Y!==t?(r.charCodeAt(v)===64?(he=c,v++):(he=t,$===0&&Pe(u)),he!==t?(te=Ge(),te!==t?(D=ie,Y=g(Y,te),ie=Y):(v=ie,ie=t)):(v=ie,ie=t)):(v=ie,ie=t),ie===t&&(ie=v,Y=fe(),Y!==t&&(D=ie,Y=f(Y)),ie=Y),ie}function fe(){var ie,Y,he,te,me;return ie=v,r.charCodeAt(v)===64?(Y=c,v++):(Y=t,$===0&&Pe(u)),Y!==t?(he=le(),he!==t?(r.charCodeAt(v)===47?(te=s,v++):(te=t,$===0&&Pe(o)),te!==t?(me=le(),me!==t?(D=ie,Y=h(),ie=Y):(v=ie,ie=t)):(v=ie,ie=t)):(v=ie,ie=t)):(v=ie,ie=t),ie===t&&(ie=v,Y=le(),Y!==t&&(D=ie,Y=h()),ie=Y),ie}function le(){var ie,Y,he;if(ie=v,Y=[],p.test(r.charAt(v))?(he=r.charAt(v),v++):(he=t,$===0&&Pe(m)),he!==t)for(;he!==t;)Y.push(he),p.test(r.charAt(v))?(he=r.charAt(v),v++):(he=t,$===0&&Pe(m));else Y=t;return Y!==t&&(D=ie,Y=h()),ie=Y,ie}function Ge(){var ie,Y,he;if(ie=v,Y=[],w.test(r.charAt(v))?(he=r.charAt(v),v++):(he=t,$===0&&Pe(B)),he!==t)for(;he!==t;)Y.push(he),w.test(r.charAt(v))?(he=r.charAt(v),v++):(he=t,$===0&&Pe(B));else Y=t;return Y!==t&&(D=ie,Y=h()),ie=Y,ie}if(z=n(),z!==t&&v===r.length)return z;throw z!==t&&v{"use strict";function H1(r){return typeof r>"u"||r===null}function she(r){return typeof r=="object"&&r!==null}function ohe(r){return Array.isArray(r)?r:H1(r)?[]:[r]}function ahe(r,e){var t,i,n,s;if(e)for(s=Object.keys(e),t=0,i=s.length;t{"use strict";function dd(r,e){Error.call(this),this.name="YAMLException",this.reason=r,this.mark=e,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}dd.prototype=Object.create(Error.prototype);dd.prototype.constructor=dd;dd.prototype.toString=function(e){var t=this.name+": ";return t+=this.reason||"(unknown reason)",!e&&this.mark&&(t+=" "+this.mark.toString()),t};G1.exports=dd});var q1=y((kZe,j1)=>{"use strict";var Y1=hc();function Ev(r,e,t,i,n){this.name=r,this.buffer=e,this.position=t,this.line=i,this.column=n}Ev.prototype.getSnippet=function(e,t){var i,n,s,o,a;if(!this.buffer)return null;for(e=e||4,t=t||75,i="",n=this.position;n>0&&`\0\r diff --git a/docs/api/actionCreatorMiddleware.mdx b/docs/api/actionCreatorMiddleware.mdx index 50570ae109..7378947a1e 100644 --- a/docs/api/actionCreatorMiddleware.mdx +++ b/docs/api/actionCreatorMiddleware.mdx @@ -53,7 +53,7 @@ import reducer from './reducer' // Augment middleware to consider all functions with a static type property to be action creators const isActionCreator = ( - action: unknown + action: unknown, ): action is Function & { type: unknown } => typeof action === 'function' && 'type' in action diff --git a/docs/api/combineSlices.mdx b/docs/api/combineSlices.mdx index b308a0e36f..81f8cb168a 100644 --- a/docs/api/combineSlices.mdx +++ b/docs/api/combineSlices.mdx @@ -235,7 +235,7 @@ declare module '.' { const withInjected = rootReducer.inject( { reducerPath: 'removable', reducer: removableReducer }, - { overrideExisting: true } + { overrideExisting: true }, ) const emptyReducer = () => null @@ -243,7 +243,7 @@ const emptyReducer = () => null const removeReducer = () => rootReducer.inject( { reducerPath: 'removable', reducer: emptyReducer }, - { overrideExisting: true } + { overrideExisting: true }, ) ``` @@ -273,14 +273,14 @@ const withCounter = rootReducer.inject(counterSlice) const selectCounterValue = (rootState: RootState) => rootState.counter?.value // number | undefined const wrappedSelectCounterValue = withCounter.selector( - (rootState) => rootState.counter.value // number + (rootState) => rootState.counter.value, // number ) console.log( selectCounterValue({}), // undefined selectCounterValue({ counter: { value: 2 } }), // 2 wrappedSelectCounterValue({}), // 0 - wrappedSelectCounterValue({ counter: { value: 2 } }) // 2 + wrappedSelectCounterValue({ counter: { value: 2 } }), // 2 ) ``` @@ -303,7 +303,7 @@ interface RootState { const selectCounterValue = withCounter.selector( (combinedState) => combinedState.counter.value, - (rootState: RootState) => rootState.innerCombined + (rootState: RootState) => rootState.innerCombined, ) console.log( @@ -316,7 +316,7 @@ console.log( value: 2, }, }, - }) // 2 + }), // 2 ) ``` @@ -365,6 +365,6 @@ If the slice state is undefined in the store state passed, the selector will ins console.log( injectedCounterSlice.selectors.selectValue({}), // 0 injectedCounterSlice.selectors.selectValue({ counter: { value: 2 } }), // 2 - aCounterSlice.selectors.selectValue({ aCounter: { value: 2 } }) // 2 + aCounterSlice.selectors.selectValue({ aCounter: { value: 2 } }), // 2 ) ``` diff --git a/docs/api/createAction.mdx b/docs/api/createAction.mdx index 15776024ae..6fbec5d955 100644 --- a/docs/api/createAction.mdx +++ b/docs/api/createAction.mdx @@ -148,6 +148,6 @@ export const epic = (actions$: Observable) => map((action) => { // action.payload can be safely used as number here (and will also be correctly inferred by TypeScript) // ... - }) + }), ) ``` diff --git a/docs/api/createAsyncThunk.mdx b/docs/api/createAsyncThunk.mdx index e837148300..67cdd33984 100644 --- a/docs/api/createAsyncThunk.mdx +++ b/docs/api/createAsyncThunk.mdx @@ -35,7 +35,7 @@ const fetchUserById = createAsyncThunk( async (userId: number, thunkAPI) => { const response = await userAPI.fetchById(userId) return response.data - } + }, ) interface UsersState { @@ -190,23 +190,23 @@ interface RejectedWithValueAction { type Pending = ( requestId: string, - arg: ThunkArg + arg: ThunkArg, ) => PendingAction type Fulfilled = ( payload: PromiseResult, requestId: string, - arg: ThunkArg + arg: ThunkArg, ) => FulfilledAction type Rejected = ( requestId: string, - arg: ThunkArg + arg: ThunkArg, ) => RejectedAction type RejectedWithValue = ( requestId: string, - arg: ThunkArg + arg: ThunkArg, ) => RejectedWithValueAction ``` @@ -365,7 +365,7 @@ const updateUser = createAsyncThunk( // by explicitly returning it using the `rejectWithValue()` utility return rejectWithValue(err.response.data) } - } + }, ) ``` @@ -391,7 +391,7 @@ const fetchUserById = createAsyncThunk( return false } }, - } + }, ) ``` @@ -419,7 +419,7 @@ export const fetchUserById = createAsyncThunk( 'fetchUserById', (userId: string) => { /* ... */ - } + }, ) // file: MyComponent.ts @@ -456,7 +456,7 @@ const fetchUserById = createAsyncThunk( signal: thunkAPI.signal, }) return await response.json() - } + }, ) ``` @@ -486,7 +486,7 @@ const readStream = createAsyncThunk( done = read.done } return result - } + }, ) ``` @@ -510,7 +510,7 @@ const fetchUserById = createAsyncThunk( cancelToken: source.token, }) return response.data - } + }, ) ``` @@ -749,7 +749,7 @@ const UsersComponent = (props: { id: string }) => { // This is an example of an onSubmit handler using Formik meant to demonstrate accessing the payload of the rejected action const handleUpdateUser = async ( values: FormValues, - formikHelpers: FormikHelpers + formikHelpers: FormikHelpers, ) => { const resultAction = await dispatch(updateUser({ id: props.id, ...values })) if (updateUser.fulfilled.match(resultAction)) { diff --git a/docs/api/createDynamicMiddleware.mdx b/docs/api/createDynamicMiddleware.mdx index 2f2150f2b6..199e8418a4 100644 --- a/docs/api/createDynamicMiddleware.mdx +++ b/docs/api/createDynamicMiddleware.mdx @@ -80,7 +80,7 @@ The "dynamic middleware instance" returned from `createDynamicMiddleware` is an ```ts no-transpile export type DynamicMiddlewareInstance< State = unknown, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > = { middleware: DynamicMiddleware addMiddleware: AddMiddleware @@ -116,7 +116,7 @@ Accepts a set of middleware, and creates an action. When dispatched, it injects ```ts no-transpile const listenerDispatch = store.dispatch( - withMiddleware(listenerMiddleware.middleware) + withMiddleware(listenerMiddleware.middleware), ) const unsubscribe = listenerDispatch(addListener({ type, effect })) @@ -131,7 +131,7 @@ _These depend on having `react-redux` installed._ ```ts no-transpile interface ReactDynamicMiddlewareInstance< State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > extends DynamicMiddlewareInstance { createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook< State, @@ -140,7 +140,7 @@ interface ReactDynamicMiddlewareInstance< createDispatchWithMiddlewareHookFactory: ( context?: Context< ReactReduxContextValue> - > + >, ) => CreateDispatchWithMiddlewareHook } ``` @@ -151,7 +151,7 @@ Accepts a set of middleware, and returns a [`useDispatch`](https://react-redux.j ```ts no-transpile const useListenerDispatch = createDispatchWithMiddlewareHook( - listenerInstance.middleware + listenerInstance.middleware, ) const Component = () => { diff --git a/docs/api/createEntityAdapter.mdx b/docs/api/createEntityAdapter.mdx index 4b9cbc4134..ffd7d19ede 100644 --- a/docs/api/createEntityAdapter.mdx +++ b/docs/api/createEntityAdapter.mdx @@ -82,7 +82,7 @@ console.log(store.getState().books) // Can create a set of memoized selectors based on the location of this entity state const booksSelectors = booksAdapter.getSelectors( - (state) => state.books + (state) => state.books, ) // And then use the selectors to retrieve values @@ -148,7 +148,7 @@ export interface EntityStateAdapter { removeMany>(state: S, keys: EntityId[]): S removeMany>( state: S, - keys: PayloadAction + keys: PayloadAction, ): S removeAll>(state: S): S @@ -156,13 +156,13 @@ export interface EntityStateAdapter { updateOne>(state: S, update: Update): S updateOne>( state: S, - update: PayloadAction> + update: PayloadAction>, ): S updateMany>(state: S, updates: Update[]): S updateMany>( state: S, - updates: PayloadAction[]> + updates: PayloadAction[]>, ): S upsertOne>(state: S, entity: T): S @@ -171,7 +171,7 @@ export interface EntityStateAdapter { upsertMany>(state: S, entities: T[]): S upsertMany>( state: S, - entities: PayloadAction + entities: PayloadAction, ): S } @@ -190,7 +190,7 @@ export interface EntityAdapter extends EntityStateAdapter { getInitialState(state: S): EntityState & S getSelectors(): EntitySelectors> getSelectors( - selectState: (state: V) => EntityState + selectState: (state: V) => EntityState, ): EntitySelectors } ``` @@ -225,7 +225,8 @@ All three options will insert _new_ entities into the list. However they differ Each method has a signature that looks like: ```ts no-transpile -(state: EntityState, argument: TypeOrPayloadAction>) => EntityState +;(state: EntityState, argument: TypeOrPayloadAction>) => + EntityState ``` In other words, they accept a state that looks like `{ids: [], entities: {}}`, and calculate and return a new state. @@ -407,7 +408,7 @@ store.dispatch( booksReceived([ { id: 'b', title: 'Book 3' }, { id: 'c', title: 'Book 2' }, - ]) + ]), ) console.log(booksSelectors.selectIds(store.getState())) diff --git a/docs/api/createListenerMiddleware.mdx b/docs/api/createListenerMiddleware.mdx index 7c626174c4..050fbd20b9 100644 --- a/docs/api/createListenerMiddleware.mdx +++ b/docs/api/createListenerMiddleware.mdx @@ -100,7 +100,7 @@ interface CreateListenerMiddlewareOptions { type ListenerErrorHandler = ( error: unknown, - errorInfo: ListenerErrorInfo + errorInfo: ListenerErrorInfo, ) => void interface ListenerErrorInfo { @@ -125,12 +125,12 @@ interface ListenerMiddlewareInstance< unknown, UnknownAction >, - ExtraArgument = unknown + ExtraArgument = unknown, > { middleware: ListenerMiddleware startListening: (options: AddListenerOptions) => Unsubscribe stopListening: ( - options: AddListenerOptions & UnsubscribeListenerOptions + options: AddListenerOptions & UnsubscribeListenerOptions, ) => boolean clearListeners: () => void } @@ -184,11 +184,11 @@ interface AddListenerOptions { type ListenerPredicate = ( action: Action, currentState?: State, - originalState?: State + originalState?: State, ) => boolean type UnsubscribeListener = ( - unsubscribeOptions?: UnsubscribeListenerOptions + unsubscribeOptions?: UnsubscribeListenerOptions, ) => void interface UnsubscribeListenerOptions { @@ -241,7 +241,7 @@ By default, this does _not_ cancel any active running instances. However, you ma ```ts no-transpile const stopListening = ( - options: AddListenerOptions & UnsubscribeListenerOptions + options: AddListenerOptions & UnsubscribeListenerOptions, ) => boolean interface UnsubscribeListenerOptions { @@ -302,7 +302,7 @@ Returns `true` if the listener entry has been removed, `false` if no subscriptio ```js const wasRemoved = store.dispatch( - removeListener({ predicate, effect, cancelActive: true }) + removeListener({ predicate, effect, cancelActive: true }), ) ``` @@ -322,7 +322,7 @@ The `listenerApi` object is the second argument to each listener callback. It co export interface ListenerEffectAPI< State, Dispatch extends ReduxDispatch, - ExtraArgument = unknown + ExtraArgument = unknown, > extends MiddlewareAPI { // NOTE: MiddlewareAPI contains `dispatch` and `getState` already @@ -579,12 +579,12 @@ The signatures are: ```ts no-transpile type ConditionFunction = ( predicate: ListenerPredicate | (() => boolean), - timeout?: number + timeout?: number, ) => Promise type TakeFunction = ( predicate: ListenerPredicate | (() => boolean), - timeout?: number + timeout?: number, ) => Promise<[Action, State, State] | null> ``` @@ -612,7 +612,7 @@ test('condition method resolves promise when there is a timeout', async () => { (action, currentState: CounterState) => { return currentState.value === 3 }, - 50 + 50, ) // In this test, we expect the timeout to happen first @@ -818,7 +818,7 @@ useEffect(() => { effect: (action, listenerApi) => { // do some useful logic here }, - }) + }), ) return unsubscribe }, []) diff --git a/docs/api/createReducer.mdx b/docs/api/createReducer.mdx index 2526b9a3d9..13a17e00ec 100644 --- a/docs/api/createReducer.mdx +++ b/docs/api/createReducer.mdx @@ -243,11 +243,11 @@ const reducer = createReducer(0, (builder) => { .addCase('increment', (state) => state + 1) .addMatcher( (action) => action.type.startsWith('i'), - (state) => state * 5 + (state) => state * 5, ) .addMatcher( (action) => action.type.endsWith('t'), - (state) => state + 2 + (state) => state + 2, ) }) diff --git a/docs/api/createSelector.mdx b/docs/api/createSelector.mdx index b0679f1ad0..f18410dae8 100644 --- a/docs/api/createSelector.mdx +++ b/docs/api/createSelector.mdx @@ -44,7 +44,7 @@ const selectSelf = (state: State) => state const unsafeSelector = createSelector(selectSelf, (state) => state.value) const draftSafeSelector = createDraftSafeSelector( selectSelf, - (state) => state.value + (state) => state.value, ) // in your reducer: @@ -81,7 +81,7 @@ const createWeakMapDraftSafeSelector = const selectSelf = (state: State) => state const draftSafeSelector = createWeakMapDraftSafeSelector( selectSelf, - (state) => state.value + (state) => state.value, ) ``` diff --git a/docs/api/createSlice.mdx b/docs/api/createSlice.mdx index 45786f3d51..577f34d75d 100644 --- a/docs/api/createSlice.mdx +++ b/docs/api/createSlice.mdx @@ -171,7 +171,7 @@ const todosSlice = createSlice({ // action type is inferred from prepare callback (state, action) => { state.todos.push(action.payload) - } + }, ), fetchTodo: create.asyncThunk( async (id: string, thunkApi) => { @@ -189,7 +189,7 @@ const todosSlice = createSlice({ state.loading = false state.todos.push(action.payload) }, - } + }, ), }), }) @@ -232,7 +232,7 @@ create.preparedReducer( }, (state, action) => { state.todos.push(action.payload) - } + }, ) ``` @@ -322,7 +322,7 @@ create.asyncThunk( error: 'Oh no!', }) } - } + }, ) ``` @@ -330,8 +330,9 @@ For common thunk API configuration options, a [`withTypes` helper](../usage/usag ```ts no-transpile reducers: (create) => { - const createAThunk = - create.asyncThunk.withTypes<{ rejectValue: { error: string } }>() + const createAThunk = create.asyncThunk.withTypes<{ + rejectValue: { error: string } + }>() return { fetchTodo: createAThunk(async (id, thunkApi) => { @@ -432,7 +433,7 @@ const counterSlice = createSlice({ reducers: (create) => ({ getCountData: create.asyncThunk(async (_arg, { getState }) => { const currentCount = counterSlice.selectors.selectValue( - getState() as RootState + getState() as RootState, ) // highlight-start // this would cause a circular type, but the type annotation breaks the circle @@ -548,7 +549,7 @@ const counterSlice = createSlice({ selectors: { selectDouble: createSelector( (sliceState: CounterState) => sliceState.value, - (value) => value * 2 + (value) => value * 2, ), }, }) @@ -568,7 +569,7 @@ console.log(selectDouble.unwrapped.recomputations) // 2 ```ts no-transpile const { selectValue } = counterSlice.getSelectors( - (rootState: RootState) => rootState.aCounter + (rootState: RootState) => rootState.aCounter, ) console.log(selectValue({ aCounter: { value: 2 } })) // 2 @@ -589,7 +590,7 @@ The [`slice.selectors`](#selectors-2) object is the equivalent of calling const { selectValue } = counterSlice.getSelectors(counterSlice.selectSlice) // or const { selectValue } = counterSlice.getSelectors( - (state: RootState) => state[counterSlice.reducerPath] + (state: RootState) => state[counterSlice.reducerPath], ) ``` diff --git a/docs/api/getDefaultEnhancers.mdx b/docs/api/getDefaultEnhancers.mdx index 6863d4168e..075e0d85fb 100644 --- a/docs/api/getDefaultEnhancers.mdx +++ b/docs/api/getDefaultEnhancers.mdx @@ -109,6 +109,6 @@ interface GetDefaultEnhancersOptions { } function getDefaultEnhancers>( - options: GetDefaultEnhancersOptions = {} + options: GetDefaultEnhancersOptions = {}, ): EnhancerArray<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions }>]> ``` diff --git a/docs/api/getDefaultMiddleware.mdx b/docs/api/getDefaultMiddleware.mdx index 7e51cf618f..921c27c2fa 100644 --- a/docs/api/getDefaultMiddleware.mdx +++ b/docs/api/getDefaultMiddleware.mdx @@ -166,6 +166,6 @@ interface GetDefaultMiddlewareOptions { } function getDefaultMiddleware( - options: GetDefaultMiddlewareOptions = {} + options: GetDefaultMiddlewareOptions = {}, ): Middleware<{}, S>[] ``` diff --git a/docs/api/matching-utilities.mdx b/docs/api/matching-utilities.mdx index 12808beecc..2c928f86a4 100644 --- a/docs/api/matching-utilities.mdx +++ b/docs/api/matching-utilities.mdx @@ -126,7 +126,7 @@ import { requestThunk1, requestThunk2 } from '@virtual/matchers' const isARejectedWithValueAction = isRejectedWithValue( requestThunk1, - requestThunk2 + requestThunk2, ) function handleRejectedWithValueAction(action: UnknownAction) { @@ -162,13 +162,13 @@ interface Interesting extends Data { } function isSpecial( - action: PayloadAction + action: PayloadAction, ): action is PayloadAction { return action.payload.isSpecial } function isInteresting( - action: PayloadAction + action: PayloadAction, ): action is PayloadAction { return action.payload.isInteresting } @@ -190,7 +190,7 @@ export const isSpecialAndInterestingThunk = createAsyncThunk( isSpecial: true, isInteresting: true, } - } + }, ) // This has unnecessary complexity @@ -224,13 +224,13 @@ const loadingReducer = createReducer(initialState, (builder) => { isAllOf(isSpecialAndInterestingThunk.fulfilled, isSpecial), (state, action) => { state.isSpecial = true - } + }, ) .addMatcher( isAllOf(isSpecialAndInterestingThunk.fulfilled, isInteresting), (state, action) => { state.isInteresting = true - } + }, ) }) ``` diff --git a/docs/components/DetailedExplanation.jsx b/docs/components/DetailedExplanation.jsx index b3701555ee..da47f48a28 100644 --- a/docs/components/DetailedExplanation.jsx +++ b/docs/components/DetailedExplanation.jsx @@ -2,7 +2,7 @@ import React from 'react' export const DetailedExplanation = ({ children, - title = 'Detailed Explanation' + title = 'Detailed Explanation', }) => { return (
diff --git a/docs/rtk-query/api/createApi.mdx b/docs/rtk-query/api/createApi.mdx index dc76754f4d..24b205556d 100644 --- a/docs/rtk-query/api/createApi.mdx +++ b/docs/rtk-query/api/createApi.mdx @@ -101,11 +101,11 @@ export type BaseQueryFn< Result = unknown, Error = unknown, DefinitionExtraOptions = {}, - Meta = {} + Meta = {}, > = ( args: Args, api: BaseQueryApi, - extraOptions: DefinitionExtraOptions + extraOptions: DefinitionExtraOptions, ) => MaybePromise> export interface BaseQueryApi { @@ -148,7 +148,7 @@ export type QueryDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = { query(arg: QueryArg): BaseQueryArg @@ -157,21 +157,21 @@ export type QueryDefinition< arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions, - baseQuery: (arg: Parameters[0]) => ReturnType + baseQuery: (arg: Parameters[0]) => ReturnType, ): MaybePromise>> /* transformResponse only available with `query`, not `queryFn` */ transformResponse?( baseQueryReturnValue: BaseQueryResult, meta: BaseQueryMeta, - arg: QueryArg + arg: QueryArg, ): ResultType | Promise /* transformErrorResponse only available with `query`, not `queryFn` */ transformErrorResponse?( baseQueryReturnValue: BaseQueryError, meta: BaseQueryMeta, - arg: QueryArg + arg: QueryArg, ): unknown extraOptions?: BaseQueryExtraOptions @@ -195,7 +195,7 @@ export type QueryDefinition< queryFulfilled, getCacheEntry, updateCachedData, // available for query endpoints only - }: QueryLifecycleApi + }: QueryLifecycleApi, ): Promise onCacheEntryAdded?( @@ -209,7 +209,7 @@ export type QueryDefinition< cacheDataLoaded, getCacheEntry, updateCachedData, // available for query endpoints only - }: QueryCacheLifecycleApi + }: QueryCacheLifecycleApi, ): Promise } ``` @@ -223,7 +223,7 @@ export type MutationDefinition< TagTypes extends string, ResultType, ReducerPath extends string = string, - Context = Record + Context = Record, > = { query(arg: QueryArg): BaseQueryArg @@ -232,21 +232,21 @@ export type MutationDefinition< arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions, - baseQuery: (arg: Parameters[0]) => ReturnType + baseQuery: (arg: Parameters[0]) => ReturnType, ): MaybePromise>> /* transformResponse only available with `query`, not `queryFn` */ transformResponse?( baseQueryReturnValue: BaseQueryResult, meta: BaseQueryMeta, - arg: QueryArg + arg: QueryArg, ): ResultType | Promise /* transformErrorResponse only available with `query`, not `queryFn` */ transformErrorResponse?( baseQueryReturnValue: BaseQueryError, meta: BaseQueryMeta, - arg: QueryArg + arg: QueryArg, ): unknown extraOptions?: BaseQueryExtraOptions @@ -262,7 +262,7 @@ export type MutationDefinition< requestId, queryFulfilled, getCacheEntry, - }: MutationLifecycleApi + }: MutationLifecycleApi, ): Promise onCacheEntryAdded?( @@ -275,7 +275,7 @@ export type MutationDefinition< cacheEntryRemoved, cacheDataLoaded, getCacheEntry, - }: MutationCacheLifecycleApi + }: MutationCacheLifecycleApi, ): Promise } ``` @@ -391,7 +391,7 @@ _(required if no `queryFn` provided)_ ```ts title="query signature" no-transpile export type query = ( - arg: QueryArg + arg: QueryArg, ) => string | Record // with `fetchBaseQuery` @@ -579,7 +579,7 @@ async function onQueryStarted( requestId, queryFulfilled, getCacheEntry, - }: MutationLifecycleApi + }: MutationLifecycleApi, ): Promise ``` @@ -594,7 +594,7 @@ async function onQueryStarted( queryFulfilled, getCacheEntry, updateCachedData, // available for query endpoints only - }: QueryLifecycleApi + }: QueryLifecycleApi, ): Promise ``` @@ -671,7 +671,7 @@ async function onCacheEntryAdded( cacheEntryRemoved, cacheDataLoaded, getCacheEntry, - }: MutationCacheLifecycleApi + }: MutationCacheLifecycleApi, ): Promise ``` @@ -687,7 +687,7 @@ async function onCacheEntryAdded( cacheDataLoaded, getCacheEntry, updateCachedData, // available for query endpoints only - }: QueryCacheLifecycleApi + }: QueryCacheLifecycleApi, ): Promise ``` diff --git a/docs/rtk-query/api/created-api/api-slice-utils.mdx b/docs/rtk-query/api/created-api/api-slice-utils.mdx index 816d5298a2..5ce2f72e07 100644 --- a/docs/rtk-query/api/created-api/api-slice-utils.mdx +++ b/docs/rtk-query/api/created-api/api-slice-utils.mdx @@ -30,13 +30,13 @@ const updateQueryData = ( endpointName: string, args: any, updateRecipe: (draft: Draft) => void, - updateProvided?: boolean -) => ThunkAction; + updateProvided?: boolean, +) => ThunkAction interface PatchCollection { - patches: Patch[]; - inversePatches: Patch[]; - undo: () => void; + patches: Patch[] + inversePatches: Patch[] + undo: () => void } ``` @@ -64,7 +64,7 @@ Note that the first two arguments (`endpointName` and `args`) are used to determ const patchCollection = dispatch( api.util.updateQueryData('getPosts', undefined, (draftPosts) => { draftPosts.push({ id: 1, name: 'Teddy' }) - }) + }), ) ``` @@ -91,7 +91,7 @@ dispatch(api.endpoints.getPosts.initiate(undefined, { ...options })) const patchCollection = dispatch( api.util.updateQueryData('getPostById', 1, (draftPost) => { draftPost.name = 'Lilly' - }) + }), ) ``` @@ -117,11 +117,8 @@ dispatch(api.endpoints.getPostById.initiate(1, { ...options })) #### Signature ```ts no-transpile -const upsertQueryData = ( - endpointName: string, - args: any, - newEntryData: T -) => ThunkAction>, PartialState, any, UnknownAction>; +const upsertQueryData = (endpointName: string, args: any, newEntryData: T) => + ThunkAction>, PartialState, any, UnknownAction> ``` - **Parameters** @@ -145,7 +142,7 @@ If dispatched while an actual request is in progress, both the upsert and reques ```ts no-transpile await dispatch( - api.util.upsertQueryData('getPost', { id: 1 }, { id: 1, text: 'Hello!' }) + api.util.upsertQueryData('getPost', { id: 1 }, { id: 1, text: 'Hello!' }), ) ``` @@ -184,12 +181,16 @@ In cases where it is desired to simply revert the previous changes, it may be pr const patchCollection = dispatch( api.util.updateQueryData('getPosts', undefined, (draftPosts) => { draftPosts.push({ id: 1, name: 'Teddy' }) - }) + }), ) // later dispatch( - api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches) + api.util.patchQueryData( + 'getPosts', + undefined, + patchCollection.inversePatches, + ), ) // or @@ -201,13 +202,10 @@ patchCollection.undo() #### Signature ```ts no-transpile -type PrefetchOptions = { ifOlderThan?: false | number } | { force?: boolean }; +type PrefetchOptions = { ifOlderThan?: false | number } | { force?: boolean } -const prefetch = ( - endpointName: string, - arg: any, - options: PrefetchOptions -) => ThunkAction; +const prefetch = (endpointName: string, arg: any, options: PrefetchOptions) => + ThunkAction ``` - **Parameters** @@ -239,7 +237,7 @@ dispatch(api.util.prefetch('getPosts', undefined, { force: true })) ```ts no-transpile function selectInvalidatedBy( state: RootState, - tags: ReadonlyArray> + tags: ReadonlyArray>, ): Array<{ endpointName: string originalArgs: any @@ -286,7 +284,7 @@ const entries = api.util.selectInvalidatedBy(state, [ ```ts no-transpile const invalidateTags = ( - tags: Array> + tags: Array>, ) => ({ type: string, payload: tags, @@ -316,7 +314,7 @@ dispatch( api.util.invalidateTags([ { type: 'Post', id: 1 }, { type: 'Post', id: 'LIST' }, - ]) + ]), ) ``` @@ -327,7 +325,7 @@ dispatch( ```ts no-transpile function selectCachedArgsForQuery( state: RootState, - queryName: QueryName + queryName: QueryName, ): Array ``` diff --git a/docs/rtk-query/api/created-api/endpoints.mdx b/docs/rtk-query/api/created-api/endpoints.mdx index ed4178467d..c57cc783fd 100644 --- a/docs/rtk-query/api/created-api/endpoints.mdx +++ b/docs/rtk-query/api/created-api/endpoints.mdx @@ -156,14 +156,14 @@ type CreateCacheSelectorFactory = | MutationResultSelectorFactory type QueryResultSelectorFactory = ( - queryArg: QueryArg | SkipToken + queryArg: QueryArg | SkipToken, ) => (state: RootState) => QueryResultSelectorResult type MutationResultSelectorFactory< Definition extends MutationDefinition, - RootState + RootState, > = ( - requestId: string | SkipToken + requestId: string | SkipToken, ) => (state: RootState) => MutationSubState & RequestStatusFlags type SkipToken = typeof Symbol @@ -200,7 +200,7 @@ function App() { // Each call will create a new selector function instance const selectPost = useMemo( () => api.endpoints.getPost.select(postId), - [postId] + [postId], ) const { data, isLoading } = useAppSelector(selectPost) // highlight-end @@ -234,14 +234,14 @@ function App() { const dispatch = useAppDispatch() const [newPost, setNewPost] = useState({ name: 'Ash' }) const [requestId, setRequestId] = useState( - skipToken + skipToken, ) // highlight-start // useMemo is used to only call `.select(..)` when required. // Each call will create a new selector function instance const selectMutationResult = useMemo( () => api.endpoints.addPost.select(requestId), - [requestId] + [requestId], ) const { isLoading } = useAppSelector(selectMutationResult) // highlight-end diff --git a/docs/rtk-query/api/created-api/hooks.mdx b/docs/rtk-query/api/created-api/hooks.mdx index d6a9426466..cd45e4951c 100644 --- a/docs/rtk-query/api/created-api/hooks.mdx +++ b/docs/rtk-query/api/created-api/hooks.mdx @@ -246,7 +246,7 @@ const useQueryResult = api.useGetPostsQuery(arg, options) ```ts no-transpile type UseQuery = ( arg: any | SkipToken, - options?: UseQueryOptions + options?: UseQueryOptions, ) => UseQueryResult type UseQueryOptions = { @@ -309,7 +309,7 @@ const useMutationResult = api.useUpdatePostMutation(options) ```ts no-transpile type UseMutation = ( - options?: UseMutationStateOptions + options?: UseMutationStateOptions, ) => [UseMutationTrigger, UseMutationResult | SelectedUseMutationResult] type UseMutationStateOptions = { @@ -387,7 +387,7 @@ const useQueryStateResult = api.endpoints.getPosts.useQueryState(arg, options) ```ts no-transpile type UseQueryState = ( arg: any | SkipToken, - options?: UseQueryStateOptions + options?: UseQueryStateOptions, ) => UseQueryStateResult | SelectedQueryStateResult type UseQueryStateOptions = { @@ -438,7 +438,7 @@ const { refetch } = api.endpoints.getPosts.useQuerySubscription(arg, options) ```ts no-transpile type UseQuerySubscription = ( arg: any | SkipToken, - options?: UseQuerySubscriptionOptions + options?: UseQuerySubscriptionOptions, ) => UseQuerySubscriptionResult type UseQuerySubscriptionOptions = { @@ -550,7 +550,7 @@ const [trigger, lastArg] = ```ts no-transpile type UseLazyQuerySubscription = ( - options?: UseLazyQuerySubscriptionOptions + options?: UseLazyQuerySubscriptionOptions, ) => [UseLazyQuerySubscriptionTrigger, LastArg] type UseLazyQuerySubscriptionOptions = { @@ -561,7 +561,7 @@ type UseLazyQuerySubscriptionOptions = { type UseLazyQuerySubscriptionTrigger = ( arg: any, - preferCacheValue?: boolean + preferCacheValue?: boolean, ) => void ``` @@ -588,7 +588,7 @@ const prefetchCallback = api.usePrefetch(endpointName, options) ```ts no-transpile type UsePrefetch = ( endpointName: string, - options?: UsePrefetchOptions + options?: UsePrefetchOptions, ) => PrefetchCallback type UsePrefetchOptions = diff --git a/docs/rtk-query/api/created-api/overview.mdx b/docs/rtk-query/api/created-api/overview.mdx index b515a2f5c8..5db80993b2 100644 --- a/docs/rtk-query/api/created-api/overview.mdx +++ b/docs/rtk-query/api/created-api/overview.mdx @@ -55,7 +55,7 @@ type Api = { > selectInvalidatedBy: ( state: FullState, - tags: Array> + tags: Array>, ) => Array<{ endpointName: string originalArgs: any @@ -63,16 +63,16 @@ type Api = { }> selectCachedArgsForQuery: ( state: FullState, - endpointName: EndpointName + endpointName: EndpointName, ) => Array resetApiState: ActionCreator getRunningQueryThunk( endpointName: EndpointName, - args: QueryArg + args: QueryArg, ): ThunkWithReturnValue getRunningMutationThunk( endpointName: EndpointName, - fixedCacheKeyOrRequestId: string + fixedCacheKeyOrRequestId: string, ): ThunkWithReturnValue getRunningQueriesThunk(): ThunkWithReturnValue< Array> diff --git a/docs/rtk-query/api/fetchBaseQuery.mdx b/docs/rtk-query/api/fetchBaseQuery.mdx index eea7ad4f37..0f668ea145 100644 --- a/docs/rtk-query/api/fetchBaseQuery.mdx +++ b/docs/rtk-query/api/fetchBaseQuery.mdx @@ -50,11 +50,11 @@ export const pokemonApi = createApi({ ```ts title="fetchBaseQuery signature" no-transpile type FetchBaseQuery = ( - args: FetchBaseQueryArgs + args: FetchBaseQueryArgs, ) => ( args: string | FetchArgs, api: BaseQueryApi, - extraOptions: ExtraOptions + extraOptions: ExtraOptions, ) => FetchBaseQueryResult type FetchBaseQueryArgs = { @@ -64,11 +64,11 @@ type FetchBaseQueryArgs = { api: Pick< BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced' - > + >, ) => MaybePromise fetchFn?: ( input: RequestInfo, - init?: RequestInit | undefined + init?: RequestInit | undefined, ) => Promise paramsSerializer?: (params: Record) => string isJsonContentType?: (headers: Headers) => boolean @@ -118,7 +118,7 @@ type prepareHeaders = ( endpoint: string type: 'query' | 'mutation' forced: boolean | undefined - } + }, ) => Headers | void ``` diff --git a/docs/rtk-query/api/setupListeners.mdx b/docs/rtk-query/api/setupListeners.mdx index 5e9fe04bef..feb44c12e0 100644 --- a/docs/rtk-query/api/setupListeners.mdx +++ b/docs/rtk-query/api/setupListeners.mdx @@ -24,8 +24,8 @@ export function setupListeners( onFocusLost: typeof onFocusLost onOnline: typeof onOnline onOffline: typeof onOffline - } - ) => () => void + }, + ) => () => void, ) { function defaultHandler() { const handleFocus = () => dispatch(onFocus()) @@ -46,7 +46,7 @@ export function setupListeners( window.addEventListener( 'visibilitychange', handleVisibilityChange, - false + false, ) window.addEventListener('focus', handleFocus, false) diff --git a/docs/rtk-query/usage-with-typescript.mdx b/docs/rtk-query/usage-with-typescript.mdx index 366da13818..178a50495e 100644 --- a/docs/rtk-query/usage-with-typescript.mdx +++ b/docs/rtk-query/usage-with-typescript.mdx @@ -103,11 +103,11 @@ export type BaseQueryFn< Result = unknown, Error = unknown, DefinitionExtraOptions = {}, - Meta = {} + Meta = {}, > = ( args: Args, api: BaseQueryApi, - extraOptions: DefinitionExtraOptions + extraOptions: DefinitionExtraOptions, ) => MaybePromise> export interface BaseQueryApi { @@ -649,7 +649,7 @@ import { FetchBaseQueryError } from '@reduxjs/toolkit/query' * Type predicate to narrow an unknown error to `FetchBaseQueryError` */ export function isFetchBaseQueryError( - error: unknown + error: unknown, ): error is FetchBaseQueryError { return typeof error === 'object' && error != null && 'status' in error } @@ -658,7 +658,7 @@ export function isFetchBaseQueryError( * Type predicate to narrow an unknown error to an object with a string 'message' property */ export function isErrorWithMessage( - error: unknown + error: unknown, ): error is { message: string } { return ( typeof error === 'object' && diff --git a/docs/rtk-query/usage/automated-refetching.mdx b/docs/rtk-query/usage/automated-refetching.mdx index 5d589934cf..846b32598d 100644 --- a/docs/rtk-query/usage/automated-refetching.mdx +++ b/docs/rtk-query/usage/automated-refetching.mdx @@ -809,8 +809,8 @@ const api = createApi({ result ? [{ type: 'Post', id }] : error?.status === 401 - ? ['UNAUTHORIZED'] - : ['UNKNOWN_ERROR'], + ? ['UNAUTHORIZED'] + : ['UNKNOWN_ERROR'], }), login: build.mutation({ query: () => '/login', @@ -908,7 +908,7 @@ import type { Post, User } from './types' // highlight-start function providesList( resultsWithIds: R | undefined, - tagType: T + tagType: T, ) { return resultsWithIds ? [ diff --git a/docs/rtk-query/usage/cache-behavior.mdx b/docs/rtk-query/usage/cache-behavior.mdx index e6815b5271..caa8774f08 100644 --- a/docs/rtk-query/usage/cache-behavior.mdx +++ b/docs/rtk-query/usage/cache-behavior.mdx @@ -138,8 +138,8 @@ const Component = () => { dispatch( api.endpoints.getPosts.initiate( { count: 5 }, - { subscribe: false, forceRefetch: true } - ) + { subscribe: false, forceRefetch: true }, + ), ) } @@ -206,7 +206,7 @@ const Component = () => { // highlight-start // this overrules the api definition setting, // forcing the query to always fetch when this component is mounted - { refetchOnMountOrArgChange: true } + { refetchOnMountOrArgChange: true }, // highlight-end ) diff --git a/docs/rtk-query/usage/code-generation.mdx b/docs/rtk-query/usage/code-generation.mdx index efd4551e05..4ee69e0d34 100644 --- a/docs/rtk-query/usage/code-generation.mdx +++ b/docs/rtk-query/usage/code-generation.mdx @@ -112,7 +112,7 @@ interface SimpleUsage { export type EndpointMatcherFunction = ( operationName: string, - operationDefinition: OperationDefinition + operationDefinition: OperationDefinition, ) => boolean ``` diff --git a/docs/rtk-query/usage/customizing-create-api.mdx b/docs/rtk-query/usage/customizing-create-api.mdx index bb1ccf4e1c..cce3b8f339 100644 --- a/docs/rtk-query/usage/customizing-create-api.mdx +++ b/docs/rtk-query/usage/customizing-create-api.mdx @@ -44,7 +44,7 @@ const customCreateApi = buildCreateApi( useSelector: createSelectorHook(MyContext), useStore: createStoreHook(MyContext), }, - }) + }), ) ``` @@ -65,7 +65,7 @@ const createLruSelector = createSelectorCreator(lruMemoize) const customCreateApi = buildCreateApi( coreModule({ createSelector: createLruSelector }), - reactHooksModule({ createSelector: createLruSelector }) + reactHooksModule({ createSelector: createLruSelector }), ) ``` @@ -94,7 +94,7 @@ declare module '../apiTypes' { BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, > { [customModuleName]: { endpoints: { diff --git a/docs/rtk-query/usage/customizing-queries.mdx b/docs/rtk-query/usage/customizing-queries.mdx index 8734cc8d2e..8532ecf26c 100644 --- a/docs/rtk-query/usage/customizing-queries.mdx +++ b/docs/rtk-query/usage/customizing-queries.mdx @@ -57,7 +57,7 @@ const customBaseQuery = ( // highlight-start args, { signal, dispatch, getState }, - extraOptions + extraOptions, // highlight-end ) => { // omitted @@ -77,7 +77,7 @@ const customBaseQuery = ( const customBaseQuery = ( args, { signal, dispatch, getState }, - extraOptions + extraOptions, ) => { // highlight-start if (Math.random() > 0.5) return { error: 'Too high!' } @@ -97,18 +97,21 @@ At its core, a `baseQuery` function only needs to have the minimum return value For [`fetchBaseQuery`](../api/fetchBaseQuery) specifically, the return type is as follows: ```ts title="Return types of fetchBaseQuery" no-transpile -Promise<{ - data: any; - error?: undefined; - meta?: { request: Request; response: Response }; -} | { - error: { - status: number; - data: any; - }; - data?: undefined; - meta?: { request: Request; response: Response }; -}> +Promise< + | { + data: any + error?: undefined + meta?: { request: Request; response: Response } + } + | { + error: { + status: number + data: any + } + data?: undefined + meta?: { request: Request; response: Response } + } +> ``` 1. ```ts title="Expected success result format with fetchBaseQuery" no-transpile @@ -130,7 +133,7 @@ By default, the payload from the server is returned directly. function defaultTransformResponse( baseQueryReturnValue: unknown, meta: unknown, - arg: unknown + arg: unknown, ) { return baseQueryReturnValue } @@ -211,7 +214,7 @@ By default, the payload from the server is returned directly. function defaultTransformResponse( baseQueryReturnValue: unknown, meta: unknown, - arg: unknown + arg: unknown, ) { return baseQueryReturnValue } @@ -232,7 +235,7 @@ dependent on the `baseQuery` used. transformErrorResponse: ( response: { data: { sideA: Tracks; sideB: Tracks } }, meta, - arg + arg, ) => { if (meta?.coinFlip === 'heads') { return response.data.sideA @@ -317,7 +320,7 @@ const queryFn = ( args, { signal, dispatch, getState }, extraOptions, - baseQuery + baseQuery, // highlight-end ) => { // omitted @@ -338,7 +341,7 @@ const queryFn = ( args, { signal, dispatch, getState }, extraOptions, - baseQuery + baseQuery, ) => { // highlight-start if (Math.random() > 0.5) return { error: 'Too high!' } @@ -362,7 +365,7 @@ import type { AxiosRequestConfig, AxiosError } from 'axios' // highlight-start const axiosBaseQuery = ( - { baseUrl }: { baseUrl: string } = { baseUrl: '' } + { baseUrl }: { baseUrl: string } = { baseUrl: '' }, ): BaseQueryFn< { url: string @@ -565,7 +568,7 @@ const baseQueryWithReauth: BaseQueryFn< const refreshResult = await baseQuery( '/refreshToken', api, - extraOptions + extraOptions, ) if (refreshResult.data) { api.dispatch(tokenReceived(refreshResult.data)) @@ -627,7 +630,7 @@ const staggeredBaseQueryWithBailOut = retry( const result = await fetchBaseQuery({ baseUrl: '/api/' })( args, api, - extraOptions + extraOptions, ) // bail out of re-tries immediately if unauthorized, @@ -640,7 +643,7 @@ const staggeredBaseQueryWithBailOut = retry( }, { maxRetries: 5, - } + }, ) // highlight-end @@ -711,7 +714,7 @@ const metaBaseQuery: BaseQueryFn< const baseResult = await fetchBaseQuery({ baseUrl: '/' })( args, api, - extraOptions + extraOptions, ) return { @@ -746,7 +749,7 @@ const api = createApi({ // These properties can be used to transform the response as desired. if (!meta) return [] return returnValue.filter( - (post) => post.timestamp >= meta.timestamp - DAY_MS + (post) => post.timestamp >= meta.timestamp - DAY_MS, ) }, // highlight-end diff --git a/docs/rtk-query/usage/manual-cache-updates.mdx b/docs/rtk-query/usage/manual-cache-updates.mdx index ac6cb96bab..7f05b88a1e 100644 --- a/docs/rtk-query/usage/manual-cache-updates.mdx +++ b/docs/rtk-query/usage/manual-cache-updates.mdx @@ -12,7 +12,7 @@ description: 'RTK Query > Usage > Manual Cache Updates: Updating and creating ca ## Overview -For most cases, in order to receive up to date data after a triggering a change in the backend, you can take advantage of cache tag invalidation to perform [automated re-fetching](./automated-refetching). This will cause a query to re-fetch its data when it has been told that a mutation has occurred which would cause its data to become out of date. +For most cases, in order to receive up to date data after a triggering a change in the backend, you can take advantage of cache tag invalidation to perform [automated re-fetching](./automated-refetching). This will cause a query to re-fetch its data when it has been told that a mutation has occurred which would cause its data to become out of date. We recommend using automated re-fetching as a preference over manual cache updates in most situations. @@ -20,7 +20,7 @@ However, there _are_ use cases when manual cache updates are necessary, such as RTK Query exports thunks for these use cases, attached to `api.utils`: -- [`updateQueryData`](../api/created-api/api-slice-utils.mdx#updatequerydata): updates an already existing cache entry +- [`updateQueryData`](../api/created-api/api-slice-utils.mdx#updatequerydata): updates an already existing cache entry - [`upsertQueryData`](../api/created-api/api-slice-utils.mdx#upsertquerydata): creates or replaces cache entries Since these are thunks, you can dispatch them anywhere you have access to `dispatch`. @@ -32,6 +32,7 @@ For updates of existing cache entries, use [`updateQueryData`](../api/created-ap `updateQueryData` is strictly intended to perform _updates_ to existing cache entries, not create new entries. If an `updateQueryData` thunk action is dispatched and the `endpointName` + `args` combination that does not match any existing cache entry, the provided `recipe` callback will not be called, and no `patches` or `inversePatches` will be returned. Use cases for manual update of cache entries: + - Providing immediate feedback to the user when a mutation is attempted - After a mutation, updating a single item in a large list of items that is already cached, rather than re-fetching the whole list - Debouncing a large number of mutations with immediate feedback as though they are being applied, followed by a single request sent to the server to update the debounced attempts @@ -42,8 +43,7 @@ To create or replace existing cache entries, use [`upsertQueryData`](../api/crea `upsertQueryData` is intended to perform _replacements_ to existing cache entries or _creation_ of new ones. Since `upsertQueryData` does not have access to the previous state of the cache entry, the update may be performed only as a replacement. In comparison, `updateQueryData` allows patching of the existing cache entry, but cannot create a new one. - -One example use case is [pessimistic updates](../usage/manual-cache-updates.mdx#pessimistic-updates). If the client makes an API call to create a `Post`, the backend could return its complete data including the `id`. Then we can use `upsertQueryData` to create a new cache entry for the `getPostById(id)` query, preventing an extra fetch to retrieve the item later. +One example use case is [pessimistic updates](../usage/manual-cache-updates.mdx#pessimistic-updates). If the client makes an API call to create a `Post`, the backend could return its complete data including the `id`. Then we can use `upsertQueryData` to create a new cache entry for the `getPostById(id)` query, preventing an extra fetch to retrieve the item later. ## Recipes @@ -102,7 +102,7 @@ const api = createApi({ const patchResult = dispatch( api.util.updateQueryData('getPost', id, (draft) => { Object.assign(draft, patch) - }) + }), ) try { await queryFulfilled @@ -197,7 +197,7 @@ const api = createApi({ const patchResult = dispatch( api.util.updateQueryData('getPost', id, (draft) => { Object.assign(draft, updatedPost) - }) + }), ) } catch {} }, @@ -214,7 +214,7 @@ const api = createApi({ try { const { data: createdPost } = await queryFulfilled const patchResult = dispatch( - api.util.upsertQueryData('getPost', id, createdPost) + api.util.upsertQueryData('getPost', id, createdPost), ) } catch {} }, @@ -253,7 +253,7 @@ function App() { const patchCollection = dispatch( api.util.updateQueryData('getPosts', undefined, (draftPosts) => { draftPosts.push({ id: 1, name: 'Teddy' }) - }) + }), ) } diff --git a/docs/rtk-query/usage/migrating-to-rtk-query.mdx b/docs/rtk-query/usage/migrating-to-rtk-query.mdx index 11b993c78b..e5f2a655bc 100644 --- a/docs/rtk-query/usage/migrating-to-rtk-query.mdx +++ b/docs/rtk-query/usage/migrating-to-rtk-query.mdx @@ -72,7 +72,7 @@ export const fetchPokemonByName = createAsyncThunk( return rejectWithValue(data) } return data - } + }, ) // highlight-end @@ -187,7 +187,7 @@ render( , // highlight-end - rootElement + rootElement, ) ``` @@ -201,7 +201,7 @@ import { AsyncThunkAction } from '@reduxjs/toolkit' import { RootState } from '../store' interface Pokemon {} export declare const fetchPokemonByName: ( - arg: string + arg: string, ) => AsyncThunkAction export const selectStatusByName = (state: RootState, name: string) => @@ -243,7 +243,7 @@ export function useGetPokemonByNameQuery(name: string) { const dispatch = useAppDispatch() // select the current status from the store state for the provided name const status = useSelector((state: RootState) => - selectStatusByName(state, name) + selectStatusByName(state, name), ) // select the current data from the store state for the provided name const data = useSelector((state: RootState) => selectDataByName(state, name)) diff --git a/docs/rtk-query/usage/mutations.mdx b/docs/rtk-query/usage/mutations.mdx index c018056832..3dd4f73f53 100644 --- a/docs/rtk-query/usage/mutations.mdx +++ b/docs/rtk-query/usage/mutations.mdx @@ -58,14 +58,14 @@ const api = createApi({ transformErrorResponse: ( response: { status: string | number }, meta, - arg + arg, ) => response.status, invalidatesTags: ['Post'], // onQueryStarted is useful for optimistic updates // The 2nd parameter is the destructured `MutationLifecycleApi` async onQueryStarted( arg, - { dispatch, getState, queryFulfilled, requestId, extra, getCacheEntry } + { dispatch, getState, queryFulfilled, requestId, extra, getCacheEntry }, ) {}, // The 2nd parameter is the destructured `MutationCacheLifecycleApi` async onCacheEntryAdded( @@ -78,7 +78,7 @@ const api = createApi({ cacheEntryRemoved, cacheDataLoaded, getCacheEntry, - } + }, ) {}, // highlight-end }), @@ -256,7 +256,7 @@ export const postApi = createApi({ result ? // successful query [ - ...result.map(({ id }) => ({ type: 'Posts', id } as const)), + ...result.map(({ id }) => ({ type: 'Posts', id }) as const), { type: 'Posts', id: 'LIST' }, ] : // an error occurred, but we still want to refetch this query when `{ type: 'Posts', id: 'LIST' }` is invalidated diff --git a/docs/rtk-query/usage/polling.mdx b/docs/rtk-query/usage/polling.mdx index 2e85c1ed6d..8a59db5ca8 100644 --- a/docs/rtk-query/usage/polling.mdx +++ b/docs/rtk-query/usage/polling.mdx @@ -34,7 +34,7 @@ In an action creator without React Hooks: const { data, status, error, refetch } = store.dispatch( endpoints.getCountById.initiate(id, { subscriptionOptions: { pollingInterval: 3000 }, - }) + }), ) ``` diff --git a/docs/rtk-query/usage/prefetching.mdx b/docs/rtk-query/usage/prefetching.mdx index fbdc3b21fb..405109fb9c 100644 --- a/docs/rtk-query/usage/prefetching.mdx +++ b/docs/rtk-query/usage/prefetching.mdx @@ -86,8 +86,8 @@ type EndpointNames = keyof typeof api.endpoints export function usePrefetchImmediately( endpoint: T, - arg: Parameters[0], - options: PrefetchOptions = {} + arg: Parameters<(typeof api.endpoints)[T]['initiate']>[0], + options: PrefetchOptions = {}, ) { const dispatch = useAppDispatch() useEffect(() => { @@ -107,7 +107,7 @@ When dispatching the `prefetch` thunk as shown below you will see the same exact ```ts title="Non-hook prefetching example" no-transpile store.dispatch( - api.util.prefetch(endpointName, arg, { force: false, ifOlderThan: 10 }) + api.util.prefetch(endpointName, arg, { force: false, ifOlderThan: 10 }), ) ``` diff --git a/docs/rtk-query/usage/queries.mdx b/docs/rtk-query/usage/queries.mdx index 1eca72047e..b0568e3047 100644 --- a/docs/rtk-query/usage/queries.mdx +++ b/docs/rtk-query/usage/queries.mdx @@ -65,7 +65,7 @@ const api = createApi({ transformErrorResponse: ( response: { status: string | number }, meta, - arg + arg, ) => response.status, providesTags: (result, error, id) => [{ type: 'Post', id }], // The 2nd parameter is the destructured `QueryLifecycleApi` @@ -79,7 +79,7 @@ const api = createApi({ queryFulfilled, getCacheEntry, updateCachedData, - } + }, ) {}, // The 2nd parameter is the destructured `QueryCacheLifecycleApi` async onCacheEntryAdded( @@ -93,7 +93,7 @@ const api = createApi({ cacheDataLoaded, getCacheEntry, updateCachedData, - } + }, ) {}, // highlight-end }), @@ -287,9 +287,7 @@ function PostsList() { return (
    - {posts?.data?.map((post) => ( - - ))} + {posts?.data?.map((post) => )}
) } @@ -346,7 +344,7 @@ If you're not using React Hooks, you can access `refetch` like this: ```ts no-transpile const { status, data, error, refetch } = dispatch( - pokemonApi.endpoints.getPokemon.initiate('bulbasaur') + pokemonApi.endpoints.getPokemon.initiate('bulbasaur'), ) ``` diff --git a/docs/rtk-query/usage/streaming-updates.mdx b/docs/rtk-query/usage/streaming-updates.mdx index 88ed09082e..880a78bfd6 100644 --- a/docs/rtk-query/usage/streaming-updates.mdx +++ b/docs/rtk-query/usage/streaming-updates.mdx @@ -78,7 +78,7 @@ export const api = createApi({ // highlight-start async onCacheEntryAdded( arg, - { updateCachedData, cacheDataLoaded, cacheEntryRemoved } + { updateCachedData, cacheDataLoaded, cacheEntryRemoved }, ) { // create a websocket connection when the cache subscription starts const ws = new WebSocket('ws://localhost:8080') @@ -165,13 +165,13 @@ export const api = createApi({ transformResponse(response: Message[]) { return messagesAdapter.addMany( messagesAdapter.getInitialState(), - response + response, ) }, // highlight-end async onCacheEntryAdded( arg, - { updateCachedData, cacheDataLoaded, cacheEntryRemoved } + { updateCachedData, cacheDataLoaded, cacheEntryRemoved }, ) { const ws = new WebSocket('ws://localhost:8080') try { diff --git a/docs/rtk-query/usage/usage-without-react-hooks.mdx b/docs/rtk-query/usage/usage-without-react-hooks.mdx index 319e4a0f95..45617d383a 100644 --- a/docs/rtk-query/usage/usage-without-react-hooks.mdx +++ b/docs/rtk-query/usage/usage-without-react-hooks.mdx @@ -71,13 +71,13 @@ Because the `endpoint.select(arg)` function returns a new selector each time it' ```ts title="Creating a memoized selector creator" no-transpile const createGetPostSelector = createSelector( (id: string) => id, - (id) => api.endpoints.getPost.select(id) + (id) => api.endpoints.getPost.select(id), ) const selectGetPostError = createSelector( (state: RootState) => state, (state: RootState, id: string) => createGetPostSelector(id), - (state, selectGetPost) => selectGetPost(state).error + (state, selectGetPost) => selectGetPost(state).error, ) ``` diff --git a/docs/tsconfig.json b/docs/tsconfig.json index 80bf4d4a7d..200ffa3ffe 100644 --- a/docs/tsconfig.json +++ b/docs/tsconfig.json @@ -18,36 +18,20 @@ "baseUrl": "..", "jsx": "preserve", "paths": { - "react": [ - "../node_modules/@types/react" - ], - "react-dom": [ - "../node_modules/@types/react-dom" - ], - "@reduxjs/toolkit": [ - "packages/toolkit/src/index.ts" - ], - "@reduxjs/toolkit/query": [ - "packages/toolkit/src/query/index.ts" - ], + "react": ["../node_modules/@types/react"], + "react-dom": ["../node_modules/@types/react-dom"], + "@reduxjs/toolkit": ["packages/toolkit/src/index.ts"], + "@reduxjs/toolkit/query": ["packages/toolkit/src/query/index.ts"], "@reduxjs/toolkit/query/react": [ - "packages/toolkit/src/query/react/index.ts" - ], - "@reduxjs/toolkit/dist/query/*": [ - "packages/toolkit/src/query/*" - ], - "@virtual/*": [ - "docs/virtual/*" - ], - "your-cool-library": [ - "docs/virtual/your-cool-library/index.ts" - ], - "redux-logger": [ - "docs/virtual/redux-logger/index.ts" + "packages/toolkit/src/query/react/index.ts", ], + "@reduxjs/toolkit/dist/query/*": ["packages/toolkit/src/query/*"], + "@virtual/*": ["docs/virtual/*"], + "your-cool-library": ["docs/virtual/your-cool-library/index.ts"], + "redux-logger": ["docs/virtual/redux-logger/index.ts"], "petstore-api.generated": [ - "docs/virtual/petstore-api.generated/index.ts" - ] - } - } -} \ No newline at end of file + "docs/virtual/petstore-api.generated/index.ts", + ], + }, + }, +} diff --git a/docs/tutorials/rtk-query.mdx b/docs/tutorials/rtk-query.mdx index 8f2c97962e..17dcbae065 100644 --- a/docs/tutorials/rtk-query.mdx +++ b/docs/tutorials/rtk-query.mdx @@ -23,7 +23,7 @@ hide_title: true ## Introduction -Welcome to the Redux Toolkit Query tutorial! **This tutorial will briefly introduce you to Redux Toolkit's "RTK Query" data fetching capability and teach you how to start using it correctly**. +Welcome to the Redux Toolkit Query tutorial! **This tutorial will briefly introduce you to Redux Toolkit's "RTK Query" data fetching capability and teach you how to start using it correctly**. :::info diff --git a/docs/usage/migrating-rtk-2.md b/docs/usage/migrating-rtk-2.md index b537ec9d41..bbdedaa9bf 100644 --- a/docs/usage/migrating-rtk-2.md +++ b/docs/usage/migrating-rtk-2.md @@ -145,7 +145,7 @@ First, the `Reducer` type now has a `PreloadedState` possible generic: ```ts type Reducer = ( state: S | PreloadedState | undefined, - action: A + action: A, ) => S ``` @@ -319,7 +319,7 @@ const customCreateApi = buildCreateApi( useDispatch: createDispatchHook(MyContext), useSelector: createSelectorHook(MyContext), useStore: createStoreHook(MyContext), - }) + }), ) // now @@ -331,7 +331,7 @@ const customCreateApi = buildCreateApi( useSelector: createSelectorHook(MyContext), useStore: createStoreHook(MyContext), }, - }) + }), ) ``` @@ -406,7 +406,7 @@ const addNumbers = createSelector( // this input selector will always return a new reference when run // so cache will never be used (a, b) => ({ a, b }), - ({ a, b }) => ({ total: a + b }) + ({ a, b }) => ({ total: a + b }), ) // instead, you should have an input selector for each stable piece of data const addNumbersStable = createSelector( @@ -414,7 +414,7 @@ const addNumbersStable = createSelector( (a, b) => b, (a, b) => ({ total: a + b, - }) + }), ) ``` @@ -537,7 +537,7 @@ const combinedReducer = combineSlices( num: numberSlice.reducer, boolean: booleanReducer, }, - api + api, ) expect(combinedReducer(undefined, dummyAction())).toEqual({ string: stringSlice.getInitialState(), @@ -564,12 +564,12 @@ const injectedReducer = combinedReducer.inject(numberSlice) // `state.number` now exists, and injectedReducer's type no longer marks it as optional expect(injectedReducer(undefined, dummyAction()).number).toBe( - numberSlice.getInitialState() + numberSlice.getInitialState(), ) // original reducer has also been changed (type is still optional) expect(combinedReducer(undefined, dummyAction()).number).toBe( - numberSlice.getInitialState() + numberSlice.getInitialState(), ) ``` @@ -603,7 +603,7 @@ const customState = { number: slice.getInitialState(), } const { selectSlice, selectMultiple } = slice.getSelectors( - (state: typeof customState) => state.number + (state: typeof customState) => state.number, ) expect(selectSlice(customState)).toBe(slice.getInitialState()) expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2) @@ -620,7 +620,7 @@ const fetchUserById = createAsyncThunk( async (userId: number, thunkAPI) => { const response = await userAPI.fetchById(userId) return response.data - } + }, ) const usersSlice = createSlice({ @@ -682,7 +682,7 @@ const todosSlice = createAppSlice({ // action type is inferred from prepare callback (state, action) => { state.todos.push(action.payload) - } + }, ), // An async thunk fetchTodo: create.asyncThunk( @@ -706,7 +706,7 @@ const todosSlice = createAppSlice({ settled: (state, action) => { state.loading = false }, - } + }, ), }), }) @@ -872,7 +872,7 @@ For example, with `redux-observable`: const epic = (action$: Observable) => action$.pipe( ofType(todoAdded), - map((action) => action) + map((action) => action), // ^? still Action ) @@ -880,7 +880,7 @@ const epic = (action$: Observable) => const epic = (action$: Observable) => action$.pipe( filter(todoAdded.match), - map((action) => action) + map((action) => action), // ^? now PayloadAction ) ``` @@ -931,7 +931,7 @@ const asyncThunkCreator = { // the definition from define() definition, // methods to modify slice - context + context, ) { const { payloadCreator, options, pending, fulfilled, rejected, settled } = definition @@ -976,7 +976,7 @@ const todoSlice = createSlice({ selectTodosByAuthor = createSelector( (state: TodoState) => state.todos, (state: TodoState, author: string) => author, - (todos, author) => todos.filter((todo) => todo.author === author) + (todos, author) => todos.filter((todo) => todo.author === author), ), }, }) @@ -991,7 +991,7 @@ export const makeSelectTodosByAuthor = () => createSelector( (state: RootState) => state.todos.todos, (state: RootState, author: string) => author, - (todos, author) => todos.filter((todo) => todo.author === author) + (todos, author) => todos.filter((todo) => todo.author === author), ) function AuthorTodos({ author }: { author: string }) { diff --git a/docs/usage/migrating-to-modern-redux.mdx b/docs/usage/migrating-to-modern-redux.mdx index 57c4758b31..4241f2d22f 100644 --- a/docs/usage/migrating-to-modern-redux.mdx +++ b/docs/usage/migrating-to-modern-redux.mdx @@ -298,7 +298,7 @@ const todosSlice = createSlice({ // In this case, `action.payload` is the default field in the action, // and can hold the `id` value - no need for `action.id` separately const matchingTodo = state.todos.find( - (todo) => todo.id === action.payload + (todo) => todo.id === action.payload, ) if (matchingTodo) { @@ -796,7 +796,7 @@ const initialState: TodosState = [] export default function todosReducer( state = initialState, - action: TodoActions + action: TodoActions, ) { switch (action.type) { // omit reducer logic @@ -944,7 +944,7 @@ const mapDispatchToProps2 = (dispatch) => { todoDeleted, todoToggled, }, - dispatch + dispatch, ) } diff --git a/docs/usage/usage-guide.md b/docs/usage/usage-guide.md index 8baf6c938a..113c732a54 100644 --- a/docs/usage/usage-guide.md +++ b/docs/usage/usage-guide.md @@ -651,7 +651,7 @@ const fetchUserById = createAsyncThunk( async (userId, thunkAPI) => { const response = await userAPI.fetchById(userId) return response.data - } + }, ) // Then, handle actions in your reducers: @@ -1084,7 +1084,7 @@ ReactDOM.render( , - document.getElementById('root') + document.getElementById('root'), ) ``` @@ -1137,10 +1137,10 @@ const store = configureStore({ ignoredActions: [ // just ignore every redux-firebase and react-redux-firebase action type ...Object.keys(rfConstants.actionTypes).map( - (type) => `${rfConstants.actionsPrefix}/${type}` + (type) => `${rfConstants.actionsPrefix}/${type}`, ), ...Object.keys(rrfActionTypes).map( - (type) => `@@reactReduxFirebase/${type}` + (type) => `@@reactReduxFirebase/${type}`, ), ], ignoredPaths: ['firebase', 'firestore'], diff --git a/docs/usage/usage-with-typescript.md b/docs/usage/usage-with-typescript.md index aadec00ccd..0194fd787e 100644 --- a/docs/usage/usage-with-typescript.md +++ b/docs/usage/usage-with-typescript.md @@ -122,7 +122,7 @@ const store = configureStore({ untypedMiddleware as Middleware< (action: Action<'specialAction'>) => number, RootState - > + >, ) // prepend and concat calls can be chained .concat(logger), @@ -213,7 +213,7 @@ createReducer(0, (builder) => }) .addCase(decrement, (state, action: PayloadAction) => { // this would error out - }) + }), ) ``` @@ -311,7 +311,7 @@ const blogSlice = createSlice({ receivedAll: { reducer( state, - action: PayloadAction + action: PayloadAction, ) { state.all = action.payload state.meta = action.meta @@ -364,7 +364,7 @@ const fetchUserById = createAsyncThunk( async (userId: number) => { const response = await fetch(`https://reqres.in/api/users/${userId}`) return (await response.json()) as Returned - } + }, ) interface UsersState { @@ -438,7 +438,7 @@ create.asyncThunk( error: 'Oh no!', }) } - } + }, ) ``` @@ -446,8 +446,9 @@ For common thunk API configuration options, a [`withTypes` helper](../usage/usag ```ts no-transpile reducers: (create) => { - const createAThunk = - create.asyncThunk.withTypes<{ rejectValue: { error: string } }>() + const createAThunk = create.asyncThunk.withTypes<{ + rejectValue: { error: string } + }>() return { fetchTodo: createAThunk(async (id, thunkApi) => { @@ -478,7 +479,7 @@ interface GenericState { const createGenericSlice = < T, - Reducers extends SliceCaseReducers> + Reducers extends SliceCaseReducers>, >({ name = '', initialState, @@ -547,7 +548,7 @@ const fetchUserById = createAsyncThunk( // Inferred return type: Promise // highlight-next-line return (await response.json()) as MyData - } + }, ) // the parameter of `fetchUserById` is automatically inferred to `number` here @@ -791,7 +792,7 @@ export const fetchArticle = createAsyncThunk( } >(data, articleEntity) return normalized.entities - } + }, ) export const slice = createSlice({ diff --git a/docs/virtual/matchers/index.ts b/docs/virtual/matchers/index.ts index 501de36c1f..ff1e4fdba5 100644 --- a/docs/virtual/matchers/index.ts +++ b/docs/virtual/matchers/index.ts @@ -1,7 +1,7 @@ import { createAsyncThunk, createReducer, - PayloadAction + PayloadAction, } from '@reduxjs/toolkit' export interface Data { @@ -18,13 +18,13 @@ export interface Interesting extends Data { } export function isSpecial( - action: PayloadAction + action: PayloadAction, ): action is PayloadAction { return action.payload.isSpecial } export function isInteresting( - action: PayloadAction + action: PayloadAction, ): action is PayloadAction { return action.payload.isInteresting } @@ -36,7 +36,7 @@ export interface ExampleState { export const initialState = { isSpecial: false, - isInteresting: false + isInteresting: false, } as ExampleState export const isSpecialAndInterestingThunk = createAsyncThunk( @@ -44,16 +44,16 @@ export const isSpecialAndInterestingThunk = createAsyncThunk( () => { return { isSpecial: true, - isInteresting: true + isInteresting: true, } - } + }, ) export const requestThunk1 = createAsyncThunk('requestThunk1', () => ({})) export const requestThunk2 = createAsyncThunk('requestThunk2', () => ({})) -export const loadingReducer = createReducer(initialState, builder => { +export const loadingReducer = createReducer(initialState, (builder) => { builder.addCase(isSpecialAndInterestingThunk.fulfilled, (state, action) => { if (isSpecial(action)) { state.isSpecial = true diff --git a/examples/action-listener/counter/public/index.html b/examples/action-listener/counter/public/index.html index c1b40227ed..5e1a99228a 100644 --- a/examples/action-listener/counter/public/index.html +++ b/examples/action-listener/counter/public/index.html @@ -1,26 +1,28 @@ - + - + Counter Example - Action Middleware -
- - - - React App - + React App + - - -
- - - - \ No newline at end of file + + diff --git a/examples/query/react/advanced/src/Pokemon.tsx b/examples/query/react/advanced/src/Pokemon.tsx index 0506e6c79a..4e848e960b 100644 --- a/examples/query/react/advanced/src/Pokemon.tsx +++ b/examples/query/react/advanced/src/Pokemon.tsx @@ -11,7 +11,7 @@ export const Pokemon = ({ name, { pollingInterval, - } + }, ) return ( diff --git a/examples/query/react/advanced/src/index.tsx b/examples/query/react/advanced/src/index.tsx index b5a9e97285..568f62e54d 100644 --- a/examples/query/react/advanced/src/index.tsx +++ b/examples/query/react/advanced/src/index.tsx @@ -10,5 +10,5 @@ const reactRoot = ReactDOM.createRoot(rootElement as HTMLElement) reactRoot.render( - + , ) diff --git a/examples/query/react/advanced/tsconfig.json b/examples/query/react/advanced/tsconfig.json index d4eea2ea4b..7f331f6806 100644 --- a/examples/query/react/advanced/tsconfig.json +++ b/examples/query/react/advanced/tsconfig.json @@ -1,25 +1,20 @@ { - "include": [ - "./src/**/*" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], - "jsx": "react-jsx", - "target": "es5", - "allowJs": true, - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "noFallthroughCasesInSwitch": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true - } -} \ No newline at end of file + "include": ["./src/**/*"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "lib": ["dom", "es2015"], + "jsx": "react-jsx", + "target": "es5", + "allowJs": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + }, +} diff --git a/examples/query/react/authentication-with-extrareducers/public/index.html b/examples/query/react/authentication-with-extrareducers/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/authentication-with-extrareducers/public/index.html +++ b/examples/query/react/authentication-with-extrareducers/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/authentication-with-extrareducers/src/features/auth/authSlice.tsx b/examples/query/react/authentication-with-extrareducers/src/features/auth/authSlice.tsx index 3c854bedad..dfbc2182ec 100644 --- a/examples/query/react/authentication-with-extrareducers/src/features/auth/authSlice.tsx +++ b/examples/query/react/authentication-with-extrareducers/src/features/auth/authSlice.tsx @@ -17,7 +17,7 @@ const slice = createSlice({ (state, { payload }) => { state.token = payload.token state.user = payload.user - } + }, ) }, }) diff --git a/examples/query/react/authentication-with-extrareducers/src/index.tsx b/examples/query/react/authentication-with-extrareducers/src/index.tsx index 2bf5b85aa3..2b302a9654 100644 --- a/examples/query/react/authentication-with-extrareducers/src/index.tsx +++ b/examples/query/react/authentication-with-extrareducers/src/index.tsx @@ -20,6 +20,6 @@ worker.start({ quiet: true }).then(() => - - ) + , + ), ) diff --git a/examples/query/react/authentication-with-extrareducers/src/mocks/handlers.ts b/examples/query/react/authentication-with-extrareducers/src/mocks/handlers.ts index 7415cb72fd..4efb7fdf88 100644 --- a/examples/query/react/authentication-with-extrareducers/src/mocks/handlers.ts +++ b/examples/query/react/authentication-with-extrareducers/src/mocks/handlers.ts @@ -11,14 +11,14 @@ export const handlers = [ ctx.json({ message: 'You shall not pass. Please login first.', }), - ctx.status(401) + ctx.status(401), ) } return res( ctx.json({ message: 'Join us on the Reactiflux Discord server in #redux if you have any questions.', - }) + }), ) }), rest.post('/login', (req, res, ctx) => { @@ -30,7 +30,7 @@ export const handlers = [ last_name: 'User', }, token, - }) + }), ) }), ] diff --git a/examples/query/react/authentication-with-extrareducers/tsconfig.json b/examples/query/react/authentication-with-extrareducers/tsconfig.json index 5f488e8e73..7f331f6806 100644 --- a/examples/query/react/authentication-with-extrareducers/tsconfig.json +++ b/examples/query/react/authentication-with-extrareducers/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -20,6 +15,6 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "noEmit": true - } + "noEmit": true, + }, } diff --git a/examples/query/react/authentication/public/index.html b/examples/query/react/authentication/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/authentication/public/index.html +++ b/examples/query/react/authentication/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/authentication/src/features/auth/authSlice.tsx b/examples/query/react/authentication/src/features/auth/authSlice.tsx index 76fde9f03c..c7d17c0bd5 100644 --- a/examples/query/react/authentication/src/features/auth/authSlice.tsx +++ b/examples/query/react/authentication/src/features/auth/authSlice.tsx @@ -14,7 +14,9 @@ const slice = createSlice({ reducers: { setCredentials: ( state, - { payload: { user, token } }: PayloadAction<{ user: User; token: string }> + { + payload: { user, token }, + }: PayloadAction<{ user: User; token: string }>, ) => { state.user = user state.token = token diff --git a/examples/query/react/authentication/src/index.tsx b/examples/query/react/authentication/src/index.tsx index b55e344e50..25df0f6d58 100644 --- a/examples/query/react/authentication/src/index.tsx +++ b/examples/query/react/authentication/src/index.tsx @@ -12,7 +12,7 @@ worker .start({ quiet: true }) .then(() => { const rootNode = ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById('root') as HTMLElement, ) return rootNode.render( @@ -24,7 +24,7 @@ worker - + , ) }) .catch(console.error) diff --git a/examples/query/react/authentication/src/mocks/handlers.ts b/examples/query/react/authentication/src/mocks/handlers.ts index 7415cb72fd..4efb7fdf88 100644 --- a/examples/query/react/authentication/src/mocks/handlers.ts +++ b/examples/query/react/authentication/src/mocks/handlers.ts @@ -11,14 +11,14 @@ export const handlers = [ ctx.json({ message: 'You shall not pass. Please login first.', }), - ctx.status(401) + ctx.status(401), ) } return res( ctx.json({ message: 'Join us on the Reactiflux Discord server in #redux if you have any questions.', - }) + }), ) }), rest.post('/login', (req, res, ctx) => { @@ -30,7 +30,7 @@ export const handlers = [ last_name: 'User', }, token, - }) + }), ) }), ] diff --git a/examples/query/react/authentication/tsconfig.json b/examples/query/react/authentication/tsconfig.json index 5f488e8e73..7f331f6806 100644 --- a/examples/query/react/authentication/tsconfig.json +++ b/examples/query/react/authentication/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -20,6 +15,6 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "noEmit": true - } + "noEmit": true, + }, } diff --git a/examples/query/react/basic/public/index.html b/examples/query/react/basic/public/index.html index 42ae2d2dcb..efbc007a8b 100644 --- a/examples/query/react/basic/public/index.html +++ b/examples/query/react/basic/public/index.html @@ -1,17 +1,19 @@ - + - - - - - - - - - - React App - + React App + - - -
- - - - \ No newline at end of file + + diff --git a/examples/query/react/basic/src/App.test.tsx b/examples/query/react/basic/src/App.test.tsx index 3225b3e090..4fd1a19675 100644 --- a/examples/query/react/basic/src/App.test.tsx +++ b/examples/query/react/basic/src/App.test.tsx @@ -18,7 +18,7 @@ describe('App', () => { }) as HTMLImageElement expect(img.src).toBe( - 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/1.png' + 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/1.png', ) }) @@ -29,8 +29,8 @@ describe('App', () => { 'https://pokeapi.co/api/v2/pokemon/bulbasaur', (req, res, ctx) => { return res(ctx.status(500)) - } - ) + }, + ), ) renderWithProviders() diff --git a/examples/query/react/basic/src/index.tsx b/examples/query/react/basic/src/index.tsx index 970d6ba2b4..589c537b24 100644 --- a/examples/query/react/basic/src/index.tsx +++ b/examples/query/react/basic/src/index.tsx @@ -7,10 +7,10 @@ import { setupStore } from './store' const store = setupStore() const reactRoot = ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById('root') as HTMLElement, ) reactRoot.render( - + , ) diff --git a/examples/query/react/basic/src/test/test-utils.tsx b/examples/query/react/basic/src/test/test-utils.tsx index cf36650812..1e90c11a87 100644 --- a/examples/query/react/basic/src/test/test-utils.tsx +++ b/examples/query/react/basic/src/test/test-utils.tsx @@ -21,7 +21,7 @@ function renderWithProviders( preloadedState = {}, store = setupStore(preloadedState), ...renderOptions - }: ExtendedRenderOptions = {} + }: ExtendedRenderOptions = {}, ) { function Wrapper({ children }: PropsWithChildren<{}>): JSX.Element { return {children} diff --git a/examples/query/react/basic/tsconfig.json b/examples/query/react/basic/tsconfig.json index d4eea2ea4b..7f331f6806 100644 --- a/examples/query/react/basic/tsconfig.json +++ b/examples/query/react/basic/tsconfig.json @@ -1,25 +1,20 @@ { - "include": [ - "./src/**/*" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], - "jsx": "react-jsx", - "target": "es5", - "allowJs": true, - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "noFallthroughCasesInSwitch": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true - } -} \ No newline at end of file + "include": ["./src/**/*"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "lib": ["dom", "es2015"], + "jsx": "react-jsx", + "target": "es5", + "allowJs": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + }, +} diff --git a/examples/query/react/conditional-fetching/public/index.html b/examples/query/react/conditional-fetching/public/index.html index 42ae2d2dcb..efbc007a8b 100644 --- a/examples/query/react/conditional-fetching/public/index.html +++ b/examples/query/react/conditional-fetching/public/index.html @@ -1,17 +1,19 @@ - + - - - - - - - - - - React App - + React App + - - -
- - - - \ No newline at end of file + + diff --git a/examples/query/react/conditional-fetching/src/Pokemon.tsx b/examples/query/react/conditional-fetching/src/Pokemon.tsx index 2e2b9549a9..077d11a4b5 100644 --- a/examples/query/react/conditional-fetching/src/Pokemon.tsx +++ b/examples/query/react/conditional-fetching/src/Pokemon.tsx @@ -8,7 +8,7 @@ export const Pokemon = ({ name }: { name: PokemonName }) => { name, { skip, - } + }, ) const SkipToggle = () => ( diff --git a/examples/query/react/conditional-fetching/src/index.tsx b/examples/query/react/conditional-fetching/src/index.tsx index 1af4cef9e5..b455864950 100644 --- a/examples/query/react/conditional-fetching/src/index.tsx +++ b/examples/query/react/conditional-fetching/src/index.tsx @@ -5,10 +5,10 @@ import App from './App' import { store } from './store' const reactRoot = ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById('root') as HTMLElement, ) reactRoot.render( - + , ) diff --git a/examples/query/react/conditional-fetching/src/pokemon.data.ts b/examples/query/react/conditional-fetching/src/pokemon.data.ts index 1617ce9e50..22eb3a0547 100644 --- a/examples/query/react/conditional-fetching/src/pokemon.data.ts +++ b/examples/query/react/conditional-fetching/src/pokemon.data.ts @@ -152,4 +152,4 @@ export const POKEMON_NAMES = [ 'mew', ] as const -export type PokemonName = typeof POKEMON_NAMES[number] +export type PokemonName = (typeof POKEMON_NAMES)[number] diff --git a/examples/query/react/conditional-fetching/tsconfig.json b/examples/query/react/conditional-fetching/tsconfig.json index d4eea2ea4b..7f331f6806 100644 --- a/examples/query/react/conditional-fetching/tsconfig.json +++ b/examples/query/react/conditional-fetching/tsconfig.json @@ -1,25 +1,20 @@ { - "include": [ - "./src/**/*" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], - "jsx": "react-jsx", - "target": "es5", - "allowJs": true, - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "noFallthroughCasesInSwitch": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true - } -} \ No newline at end of file + "include": ["./src/**/*"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "lib": ["dom", "es2015"], + "jsx": "react-jsx", + "target": "es5", + "allowJs": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + }, +} diff --git a/examples/query/react/deduping-queries/public/index.html b/examples/query/react/deduping-queries/public/index.html index 42ae2d2dcb..efbc007a8b 100644 --- a/examples/query/react/deduping-queries/public/index.html +++ b/examples/query/react/deduping-queries/public/index.html @@ -1,17 +1,19 @@ - + - - - - - - - - - - React App - + React App + - - -
- - - - \ No newline at end of file + + diff --git a/examples/query/react/deduping-queries/src/Pokemon.tsx b/examples/query/react/deduping-queries/src/Pokemon.tsx index 624602f3a9..73e71925bd 100644 --- a/examples/query/react/deduping-queries/src/Pokemon.tsx +++ b/examples/query/react/deduping-queries/src/Pokemon.tsx @@ -1,13 +1,8 @@ import { useGetPokemonByNameQuery } from './services/pokemon' export const Pokemon = ({ name }: { name: string }) => { - const { - data, - error, - isLoading, - isFetching, - refetch, - } = useGetPokemonByNameQuery(name) + const { data, error, isLoading, isFetching, refetch } = + useGetPokemonByNameQuery(name) return (
diff --git a/examples/query/react/deduping-queries/src/index.tsx b/examples/query/react/deduping-queries/src/index.tsx index 0924558a7d..b36d809053 100644 --- a/examples/query/react/deduping-queries/src/index.tsx +++ b/examples/query/react/deduping-queries/src/index.tsx @@ -5,11 +5,11 @@ import App from './App' import { store } from './store' const reactRoot = ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById('root') as HTMLElement, ) reactRoot.render( - + , ) diff --git a/examples/query/react/deduping-queries/tsconfig.json b/examples/query/react/deduping-queries/tsconfig.json index d4eea2ea4b..7f331f6806 100644 --- a/examples/query/react/deduping-queries/tsconfig.json +++ b/examples/query/react/deduping-queries/tsconfig.json @@ -1,25 +1,20 @@ { - "include": [ - "./src/**/*" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], - "jsx": "react-jsx", - "target": "es5", - "allowJs": true, - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "noFallthroughCasesInSwitch": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true - } -} \ No newline at end of file + "include": ["./src/**/*"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "lib": ["dom", "es2015"], + "jsx": "react-jsx", + "target": "es5", + "allowJs": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + }, +} diff --git a/examples/query/react/graphql-codegen/.introspection.json b/examples/query/react/graphql-codegen/.introspection.json index 00aa67088e..732fa070df 100644 --- a/examples/query/react/graphql-codegen/.introspection.json +++ b/examples/query/react/graphql-codegen/.introspection.json @@ -1704,11 +1704,7 @@ "name": "include", "description": "Directs the executor to include this field or fragment only when the `if` argument is true.", "isRepeatable": false, - "locations": [ - "FIELD", - "FRAGMENT_SPREAD", - "INLINE_FRAGMENT" - ], + "locations": ["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"], "args": [ { "name": "if", @@ -1732,11 +1728,7 @@ "name": "skip", "description": "Directs the executor to skip this field or fragment when the `if` argument is true.", "isRepeatable": false, - "locations": [ - "FIELD", - "FRAGMENT_SPREAD", - "INLINE_FRAGMENT" - ], + "locations": ["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"], "args": [ { "name": "if", @@ -1785,9 +1777,7 @@ "name": "specifiedBy", "description": "Exposes a URL that specifies the behaviour of this scalar.", "isRepeatable": false, - "locations": [ - "SCALAR" - ], + "locations": ["SCALAR"], "args": [ { "name": "url", @@ -1809,4 +1799,4 @@ } ] } -} \ No newline at end of file +} diff --git a/examples/query/react/graphql-codegen/public/index.html b/examples/query/react/graphql-codegen/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/graphql-codegen/public/index.html +++ b/examples/query/react/graphql-codegen/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/graphql-codegen/src/app/services/types.generated.ts b/examples/query/react/graphql-codegen/src/app/services/types.generated.ts index f1f88bfc20..399ebbd2c9 100644 --- a/examples/query/react/graphql-codegen/src/app/services/types.generated.ts +++ b/examples/query/react/graphql-codegen/src/app/services/types.generated.ts @@ -1,119 +1,118 @@ -export type Maybe = T; -export type Exact = { [K in keyof T]: T[K] }; -export type MakeOptional = Omit & { [SubKey in K]?: Maybe }; -export type MakeMaybe = Omit & { [SubKey in K]: Maybe }; +export type Maybe = T +export type Exact = { + [K in keyof T]: T[K] +} +export type MakeOptional = Omit & { + [SubKey in K]?: Maybe +} +export type MakeMaybe = Omit & { + [SubKey in K]: Maybe +} /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { - ID: string; - String: string; - Boolean: boolean; - Int: number; - Float: number; -}; + ID: string + String: string + Boolean: boolean + Int: number + Float: number +} export type IdQueryType = { - equals?: Maybe; - notEquals?: Maybe; - contains?: Maybe; - notContains?: Maybe; - in?: Maybe; - notIn?: Maybe; -}; + equals?: Maybe + notEquals?: Maybe + contains?: Maybe + notContains?: Maybe + in?: Maybe + notIn?: Maybe +} export type Mutation = { - __typename?: 'Mutation'; - createPost?: Maybe; - updatePost?: Maybe; - updatePosts?: Maybe>>; - deletePost?: Maybe; - deletePosts?: Maybe>>; -}; - + __typename?: 'Mutation' + createPost?: Maybe + updatePost?: Maybe + updatePosts?: Maybe>> + deletePost?: Maybe + deletePosts?: Maybe>> +} export type MutationCreatePostArgs = { - data?: Maybe; -}; - + data?: Maybe +} export type MutationUpdatePostArgs = { - where?: Maybe; - data?: Maybe; -}; - + where?: Maybe + data?: Maybe +} export type MutationUpdatePostsArgs = { - where?: Maybe; - data?: Maybe; -}; - + where?: Maybe + data?: Maybe +} export type MutationDeletePostArgs = { - where?: Maybe; -}; - + where?: Maybe +} export type MutationDeletePostsArgs = { - where?: Maybe; -}; + where?: Maybe +} export type Post = { - __typename?: 'Post'; - id?: Maybe; - name?: Maybe; - title?: Maybe; - author?: Maybe; - content?: Maybe; - status?: Maybe; - created_at?: Maybe; - updated_at?: Maybe; -}; + __typename?: 'Post' + id?: Maybe + name?: Maybe + title?: Maybe + author?: Maybe + content?: Maybe + status?: Maybe + created_at?: Maybe + updated_at?: Maybe +} export type PostInput = { - id?: Maybe; - name?: Maybe; - title?: Maybe; - author?: Maybe; - content?: Maybe; - status?: Maybe; - created_at?: Maybe; - updated_at?: Maybe; -}; + id?: Maybe + name?: Maybe + title?: Maybe + author?: Maybe + content?: Maybe + status?: Maybe + created_at?: Maybe + updated_at?: Maybe +} export type PostQueryInput = { - id?: Maybe; - name?: Maybe; - title?: Maybe; - author?: Maybe; - content?: Maybe; - status?: Maybe; - created_at?: Maybe; - updated_at?: Maybe; -}; + id?: Maybe + name?: Maybe + title?: Maybe + author?: Maybe + content?: Maybe + status?: Maybe + created_at?: Maybe + updated_at?: Maybe +} export type Query = { - __typename?: 'Query'; - post?: Maybe; - posts?: Maybe>>; -}; - + __typename?: 'Query' + post?: Maybe + posts?: Maybe>> +} export type QueryPostArgs = { - where?: Maybe; -}; - + where?: Maybe +} export type QueryPostsArgs = { - take?: Maybe; - skip?: Maybe; - cursor?: Maybe; - where?: Maybe; -}; + take?: Maybe + skip?: Maybe + cursor?: Maybe + where?: Maybe +} export type StringQueryType = { - equals?: Maybe; - notEquals?: Maybe; - contains?: Maybe; - notContains?: Maybe; - in?: Maybe; - notIn?: Maybe; -}; + equals?: Maybe + notEquals?: Maybe + contains?: Maybe + notContains?: Maybe + in?: Maybe + notIn?: Maybe +} diff --git a/examples/query/react/graphql-codegen/src/features/posts/GetPost.generated.ts b/examples/query/react/graphql-codegen/src/features/posts/GetPost.generated.ts index 17a3fd7999..0ed9677e3c 100644 --- a/examples/query/react/graphql-codegen/src/features/posts/GetPost.generated.ts +++ b/examples/query/react/graphql-codegen/src/features/posts/GetPost.generated.ts @@ -9,23 +9,19 @@ * for this file to be re-created */ -import * as Types from '../../app/services/types.generated'; +import * as Types from '../../app/services/types.generated' -import { api } from 'app/services/baseApi'; -module.hot?.accept(); +import { api } from 'app/services/baseApi' +module.hot?.accept() export type GetPostQueryVariables = Types.Exact<{ - id: Types.Scalars['ID']; -}>; - - -export type GetPostQuery = ( - { __typename?: 'Query' } - & { post?: Types.Maybe<( - { __typename?: 'Post' } - & Pick - )> } -); + id: Types.Scalars['ID'] +}> +export type GetPostQuery = { __typename?: 'Query' } & { + post?: Types.Maybe< + { __typename?: 'Post' } & Pick + > +} export const GetPostDocument = ` query GetPost($id: ID!) { @@ -35,17 +31,16 @@ export const GetPostDocument = ` content } } - `; + ` const injectedRtkApi = api.injectEndpoints({ - overrideExisting: module.hot?.status() === "apply", + overrideExisting: module.hot?.status() === 'apply', endpoints: (build) => ({ GetPost: build.query({ - query: (variables) => ({ document: GetPostDocument, variables }) + query: (variables) => ({ document: GetPostDocument, variables }), }), }), -}); - -export { injectedRtkApi as api }; -export const { useGetPostQuery, useLazyGetPostQuery } = injectedRtkApi; +}) +export { injectedRtkApi as api } +export const { useGetPostQuery, useLazyGetPostQuery } = injectedRtkApi diff --git a/examples/query/react/graphql-codegen/src/features/posts/GetPosts.generated.ts b/examples/query/react/graphql-codegen/src/features/posts/GetPosts.generated.ts index 79c42956e0..6efed203a6 100644 --- a/examples/query/react/graphql-codegen/src/features/posts/GetPosts.generated.ts +++ b/examples/query/react/graphql-codegen/src/features/posts/GetPosts.generated.ts @@ -9,24 +9,24 @@ * for this file to be re-created */ -import * as Types from '../../app/services/types.generated'; +import * as Types from '../../app/services/types.generated' -import { api } from 'app/services/baseApi'; -module.hot?.accept(); +import { api } from 'app/services/baseApi' +module.hot?.accept() export type GetPostsQueryVariables = Types.Exact<{ - skip?: Types.Maybe; - take?: Types.Maybe; -}>; - - -export type GetPostsQuery = ( - { __typename?: 'Query' } - & { posts?: Types.Maybe - )>>> } -); - + skip?: Types.Maybe + take?: Types.Maybe +}> + +export type GetPostsQuery = { __typename?: 'Query' } & { + posts?: Types.Maybe< + Array< + Types.Maybe< + { __typename?: 'Post' } & Pick + > + > + > +} export const GetPostsDocument = ` query GetPosts($skip: Int = 0, $take: Int = 10) { @@ -36,17 +36,16 @@ export const GetPostsDocument = ` status } } - `; + ` const injectedRtkApi = api.injectEndpoints({ - overrideExisting: module.hot?.status() === "apply", + overrideExisting: module.hot?.status() === 'apply', endpoints: (build) => ({ GetPosts: build.query({ - query: (variables) => ({ document: GetPostsDocument, variables }) + query: (variables) => ({ document: GetPostsDocument, variables }), }), }), -}); - -export { injectedRtkApi as api }; -export const { useGetPostsQuery, useLazyGetPostsQuery } = injectedRtkApi; +}) +export { injectedRtkApi as api } +export const { useGetPostsQuery, useLazyGetPostsQuery } = injectedRtkApi diff --git a/examples/query/react/graphql-codegen/src/features/posts/PostsManager.tsx b/examples/query/react/graphql-codegen/src/features/posts/PostsManager.tsx index 907d412679..9eefa7bf48 100644 --- a/examples/query/react/graphql-codegen/src/features/posts/PostsManager.tsx +++ b/examples/query/react/graphql-codegen/src/features/posts/PostsManager.tsx @@ -23,8 +23,8 @@ const getColorForStatus = (status: string | undefined) => { return status === 'draft' ? 'gray' : status === 'pending_review' - ? 'orange' - : 'green' + ? 'orange' + : 'green' } const PostList = () => { diff --git a/examples/query/react/graphql-codegen/src/index.tsx b/examples/query/react/graphql-codegen/src/index.tsx index 88e4ff607c..a3f9271c5c 100644 --- a/examples/query/react/graphql-codegen/src/index.tsx +++ b/examples/query/react/graphql-codegen/src/index.tsx @@ -11,7 +11,7 @@ import { ApiProvider } from '@reduxjs/toolkit/query/react' // Initialize the msw worker, wait for the service worker registration to resolve, then mount worker.start({ quiet: true }).then(() => { return ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById('root') as HTMLElement, ).render( @@ -21,6 +21,6 @@ worker.start({ quiet: true }).then(() => { - + , ) }) diff --git a/examples/query/react/graphql-codegen/src/mocks/db.ts b/examples/query/react/graphql-codegen/src/mocks/db.ts index fededb9d62..78341ab30a 100644 --- a/examples/query/react/graphql-codegen/src/mocks/db.ts +++ b/examples/query/react/graphql-codegen/src/mocks/db.ts @@ -9,7 +9,7 @@ interface Post { title: string author: string content: string - status: typeof postStatuses[number] + status: (typeof postStatuses)[number] created_at: string updated_at: string } diff --git a/examples/query/react/graphql-codegen/tsconfig.json b/examples/query/react/graphql-codegen/tsconfig.json index 93e52d5db1..16a99dca49 100644 --- a/examples/query/react/graphql-codegen/tsconfig.json +++ b/examples/query/react/graphql-codegen/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -21,6 +16,6 @@ "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, - "baseUrl": "src" - } + "baseUrl": "src", + }, } diff --git a/examples/query/react/graphql/public/index.html b/examples/query/react/graphql/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/graphql/public/index.html +++ b/examples/query/react/graphql/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/graphql/src/app/services/posts.ts b/examples/query/react/graphql/src/app/services/posts.ts index fbbcf0de02..0d84c75f2c 100644 --- a/examples/query/react/graphql/src/app/services/posts.ts +++ b/examples/query/react/graphql/src/app/services/posts.ts @@ -1,6 +1,6 @@ -import { createApi } from '@reduxjs/toolkit/query/react' +import { createApi } from '@reduxjs/toolkit/query/react' import { gql } from 'graphql-request' -import {graphqlRequestBaseQuery} from '@rtk-query/graphql-request-base-query' +import { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query' export const postStatuses = ['draft', 'published', 'pending_review'] as const @@ -9,7 +9,7 @@ export interface Post { title: string author: string content: string - status: typeof postStatuses[number] + status: (typeof postStatuses)[number] created_at: string updated_at: string } diff --git a/examples/query/react/graphql/src/features/posts/PostsManager.tsx b/examples/query/react/graphql/src/features/posts/PostsManager.tsx index e16e6ac46c..8203ed4b3b 100644 --- a/examples/query/react/graphql/src/features/posts/PostsManager.tsx +++ b/examples/query/react/graphql/src/features/posts/PostsManager.tsx @@ -23,8 +23,8 @@ const getColorForStatus = (status: Post['status']) => { return status === 'draft' ? 'gray' : status === 'pending_review' - ? 'orange' - : 'green' + ? 'orange' + : 'green' } const PostList = () => { diff --git a/examples/query/react/graphql/src/index.tsx b/examples/query/react/graphql/src/index.tsx index a7429fe087..db33bb49a1 100644 --- a/examples/query/react/graphql/src/index.tsx +++ b/examples/query/react/graphql/src/index.tsx @@ -11,7 +11,7 @@ import { ApiProvider } from '@reduxjs/toolkit/query/react' // Initialize the msw worker, wait for the service worker registration to resolve, then mount worker.start({ quiet: true }).then(() => { return ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById('root') as HTMLElement, ).render( @@ -21,6 +21,6 @@ worker.start({ quiet: true }).then(() => { - + , ) }) diff --git a/examples/query/react/graphql/src/mocks/db.ts b/examples/query/react/graphql/src/mocks/db.ts index 0aa6a3c2a4..2ba757e6fe 100644 --- a/examples/query/react/graphql/src/mocks/db.ts +++ b/examples/query/react/graphql/src/mocks/db.ts @@ -37,7 +37,8 @@ const createPostData = (): Post => { ;[...new Array(50)].forEach((_) => db.post.create(createPostData())) type PaginationOptions = { - page: number; per_page: number + page: number + per_page: number } interface Posts extends Pagination { @@ -52,19 +53,19 @@ export const handlers = [ const posts = db.post.findMany({ take: per_page, - skip: Math.max(per_page * (page - 1), 0) + skip: Math.max(per_page * (page - 1), 0), }) return res( ctx.data({ data: { - posts + posts, } as { posts: Post[] }, per_page, page, total_pages: Math.ceil(db.post.count() / per_page), total: db.post.count(), - }) + }), ) }), ...db.post.toHandlers('graphql'), diff --git a/examples/query/react/graphql/tsconfig.json b/examples/query/react/graphql/tsconfig.json index 5f488e8e73..7f331f6806 100644 --- a/examples/query/react/graphql/tsconfig.json +++ b/examples/query/react/graphql/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -20,6 +15,6 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "noEmit": true - } + "noEmit": true, + }, } diff --git a/examples/query/react/kitchen-sink/public/index.html b/examples/query/react/kitchen-sink/public/index.html index 42ae2d2dcb..efbc007a8b 100644 --- a/examples/query/react/kitchen-sink/public/index.html +++ b/examples/query/react/kitchen-sink/public/index.html @@ -1,17 +1,19 @@ - + - - - - - - - - - - React App - + React App + - - -
- - - - \ No newline at end of file + + diff --git a/examples/query/react/kitchen-sink/src/app/services/api.ts b/examples/query/react/kitchen-sink/src/app/services/api.ts index e9c9ab0c56..0cd4e2e692 100644 --- a/examples/query/react/kitchen-sink/src/app/services/api.ts +++ b/examples/query/react/kitchen-sink/src/app/services/api.ts @@ -20,7 +20,7 @@ const baseQueryWithRetry = retry(baseQuery, { maxRetries: 6 }) * Create a base API to inject endpoints into elsewhere. * Components using this API should import from the injected site, * in order to get the appropriate types, - * and to ensure that the file injecting the endpoints is loaded + * and to ensure that the file injecting the endpoints is loaded */ export const api = createApi({ /** diff --git a/examples/query/react/kitchen-sink/src/app/services/posts.ts b/examples/query/react/kitchen-sink/src/app/services/posts.ts index 08204d0062..04293c4237 100644 --- a/examples/query/react/kitchen-sink/src/app/services/posts.ts +++ b/examples/query/react/kitchen-sink/src/app/services/posts.ts @@ -34,7 +34,7 @@ export const postsApi = api.injectEndpoints({ getPosts: build.query({ query: () => ({ url: 'posts' }), providesTags: (result = []) => [ - ...result.map(({ id }) => ({ type: 'Posts', id } as const)), + ...result.map(({ id }) => ({ type: 'Posts', id }) as const), { type: 'Posts' as const, id: 'LIST' }, ], }), diff --git a/examples/query/react/kitchen-sink/src/app/store.ts b/examples/query/react/kitchen-sink/src/app/store.ts index 82232113dc..e814615c9f 100644 --- a/examples/query/react/kitchen-sink/src/app/store.ts +++ b/examples/query/react/kitchen-sink/src/app/store.ts @@ -5,7 +5,7 @@ import polling from '../features/polling/pollingSlice' import auth from '../features/auth/authSlice' export const createStore = ( - options?: ConfigureStoreOptions['preloadedState'] | undefined + options?: ConfigureStoreOptions['preloadedState'] | undefined, ) => configureStore({ reducer: { diff --git a/examples/query/react/kitchen-sink/src/features/bundleSplitting/Post.tsx b/examples/query/react/kitchen-sink/src/features/bundleSplitting/Post.tsx index ececa81173..fe7de3c6cb 100644 --- a/examples/query/react/kitchen-sink/src/features/bundleSplitting/Post.tsx +++ b/examples/query/react/kitchen-sink/src/features/bundleSplitting/Post.tsx @@ -16,10 +16,7 @@ const Post = ({ id }: { id: number }) => { * This missing would be a programming error that you should * catch early anyways. */ - assert( - postApi.endpoints.getPost?.useQuery, - 'Endpoint `getPost` not loaded!' - ) + assert(postApi.endpoints.getPost?.useQuery, 'Endpoint `getPost` not loaded!') const { data, error } = postApi.endpoints.getPost.useQuery(id) return error ? ( <>there was an error diff --git a/examples/query/react/kitchen-sink/src/features/bundleSplitting/PostsList.tsx b/examples/query/react/kitchen-sink/src/features/bundleSplitting/PostsList.tsx index fc9452a7c5..2c8539fe9a 100644 --- a/examples/query/react/kitchen-sink/src/features/bundleSplitting/PostsList.tsx +++ b/examples/query/react/kitchen-sink/src/features/bundleSplitting/PostsList.tsx @@ -1,7 +1,7 @@ -import * as React from 'react'; +import * as React from 'react' -import { Post } from '.'; -import { postsApi } from '../../app/services/posts'; +import { Post } from '.' +import { postsApi } from '../../app/services/posts' const PostsList = () => { /** @@ -13,8 +13,8 @@ const PostsList = () => { * injected though. */ - const { data, error } = postsApi.endpoints.getPosts.useQuery(); - const [selected, select] = React.useState(); + const { data, error } = postsApi.endpoints.getPosts.useQuery() + const [selected, select] = React.useState() return error ? ( <>there was an error ) : !data ? ( @@ -30,6 +30,6 @@ const PostsList = () => { ))} - ); -}; -export default PostsList; + ) +} +export default PostsList diff --git a/examples/query/react/kitchen-sink/src/features/counter/Counter.module.css b/examples/query/react/kitchen-sink/src/features/counter/Counter.module.css index 2ba30ae792..7e60ca1c7f 100644 --- a/examples/query/react/kitchen-sink/src/features/counter/Counter.module.css +++ b/examples/query/react/kitchen-sink/src/features/counter/Counter.module.css @@ -13,7 +13,7 @@ padding-left: 16px; padding-right: 16px; margin-top: 2px; - font-family: "Courier New", Courier, monospace; + font-family: 'Courier New', Courier, monospace; } .button { @@ -56,7 +56,7 @@ } .asyncButton:after { - content: ""; + content: ''; background-color: rgba(112, 76, 182, 0.15); display: block; position: absolute; @@ -65,7 +65,9 @@ left: 0; top: 0; opacity: 0; - transition: width 1s linear, opacity 0.5s ease 1s; + transition: + width 1s linear, + opacity 0.5s ease 1s; } .asyncButton:active:after { diff --git a/examples/query/react/kitchen-sink/src/features/counter/Counter.tsx b/examples/query/react/kitchen-sink/src/features/counter/Counter.tsx index c192e40ca2..ed8c5bf357 100644 --- a/examples/query/react/kitchen-sink/src/features/counter/Counter.tsx +++ b/examples/query/react/kitchen-sink/src/features/counter/Counter.tsx @@ -1,32 +1,52 @@ -import React, { useState } from 'react'; -import styles from './Counter.module.css'; -import { useDecrementCountMutation, useGetCountQuery, useIncrementCountMutation } from '../../app/services/counter'; +import React, { useState } from 'react' +import styles from './Counter.module.css' +import { + useDecrementCountMutation, + useGetCountQuery, + useIncrementCountMutation, +} from '../../app/services/counter' -export function Counter({ id, onRemove }: { id?: string; onRemove?: () => void }) { - const [pollingInterval, setPollingInterval] = useState(10000); - const { data } = useGetCountQuery(undefined, { pollingInterval }); - const [increment] = useIncrementCountMutation(); +export function Counter({ + id, + onRemove, +}: { + id?: string + onRemove?: () => void +}) { + const [pollingInterval, setPollingInterval] = useState(10000) + const { data } = useGetCountQuery(undefined, { pollingInterval }) + const [increment] = useIncrementCountMutation() - const [decrement] = useDecrementCountMutation(); + const [decrement] = useDecrementCountMutation() return (
- {data?.count || 0} - setPollingInterval(valueAsNumber)} + onChange={({ target: { valueAsNumber } }) => + setPollingInterval(valueAsNumber) + } /> {onRemove && }
- ); + ) } diff --git a/examples/query/react/kitchen-sink/src/features/counter/CounterList.tsx b/examples/query/react/kitchen-sink/src/features/counter/CounterList.tsx index e917b72140..acf946b93b 100644 --- a/examples/query/react/kitchen-sink/src/features/counter/CounterList.tsx +++ b/examples/query/react/kitchen-sink/src/features/counter/CounterList.tsx @@ -1,30 +1,38 @@ -import * as React from 'react'; -import { nanoid } from '@reduxjs/toolkit'; -import { Container } from '../common/Container'; -import { Counter } from './Counter'; +import * as React from 'react' +import { nanoid } from '@reduxjs/toolkit' +import { Container } from '../common/Container' +import { Counter } from './Counter' export const CounterList = () => { - const [counters, setCounters] = React.useState([]); + const [counters, setCounters] = React.useState([]) if (!counters.length) { return (
No counters, why don't you add one?
- +
- ); + ) } return (
- +
{counters.map((id) => ( - setCounters((prev) => prev.filter((el) => el !== id))} /> + setCounters((prev) => prev.filter((el) => el !== id))} + /> ))}
- ); -}; + ) +} diff --git a/examples/query/react/kitchen-sink/src/features/polling/PollingToggles.tsx b/examples/query/react/kitchen-sink/src/features/polling/PollingToggles.tsx index dca03216bd..c67ddc7910 100644 --- a/examples/query/react/kitchen-sink/src/features/polling/PollingToggles.tsx +++ b/examples/query/react/kitchen-sink/src/features/polling/PollingToggles.tsx @@ -1,47 +1,59 @@ -import * as React from 'react'; -import { useAppDispatch, useTypedSelector } from '../../app/store'; +import * as React from 'react' +import { useAppDispatch, useTypedSelector } from '../../app/store' import { selectGlobalPollingEnabled, selectPollingConfigByApp, toggleGlobalPolling, updatePolling, -} from './pollingSlice'; +} from './pollingSlice' const PollingToggleButton = ({ enabled, onClick, children, }: { - onClick: () => void; - enabled: boolean; - children?: React.ReactNode; + onClick: () => void + enabled: boolean + children?: React.ReactNode }) => { return ( - - ); -}; + ) +} export const PollingToggles = () => { - const dispatch = useAppDispatch(); - const globalPolling = useTypedSelector(selectGlobalPollingEnabled); - const timesPolling = useTypedSelector((state) => selectPollingConfigByApp(state, 'times')); + const dispatch = useAppDispatch() + const globalPolling = useTypedSelector(selectGlobalPollingEnabled) + const timesPolling = useTypedSelector((state) => + selectPollingConfigByApp(state, 'times'), + ) return (
Global Polling Configs
- dispatch(toggleGlobalPolling())}> + dispatch(toggleGlobalPolling())} + > Global dispatch(updatePolling({ app: 'times', enabled: !timesPolling.enabled }))} + onClick={() => + dispatch( + updatePolling({ app: 'times', enabled: !timesPolling.enabled }), + ) + } > Times
- ); -}; + ) +} diff --git a/examples/query/react/kitchen-sink/src/features/polling/pollingSlice.ts b/examples/query/react/kitchen-sink/src/features/polling/pollingSlice.ts index e193c3ba01..0a43c7a474 100644 --- a/examples/query/react/kitchen-sink/src/features/polling/pollingSlice.ts +++ b/examples/query/react/kitchen-sink/src/features/polling/pollingSlice.ts @@ -1,17 +1,17 @@ -import { createSlice, PayloadAction } from '@reduxjs/toolkit'; -import type { RootState } from '../../app/store'; +import { createSlice, PayloadAction } from '@reduxjs/toolkit' +import type { RootState } from '../../app/store' type PollingConfig = { - enabled: boolean; - interval: number; -}; + enabled: boolean + interval: number +} type SliceState = { - enabled: boolean; + enabled: boolean apps: { - [key: string]: PollingConfig; - }; -}; + [key: string]: PollingConfig + } +} const initialState: SliceState = { enabled: true, @@ -29,39 +29,43 @@ const initialState: SliceState = { interval: 0, }, }, -}; +} -type PollingAppKey = keyof typeof initialState['apps']; +type PollingAppKey = keyof (typeof initialState)['apps'] const slice = createSlice({ name: 'polling', initialState, reducers: { toggleGlobalPolling(state) { - state.enabled = !state.enabled; + state.enabled = !state.enabled }, updatePolling( state, { payload, }: PayloadAction<{ - app: PollingAppKey; - enabled?: boolean; - interval?: number; - }> + app: PollingAppKey + enabled?: boolean + interval?: number + }>, ) { - const { app, ...rest } = payload; + const { app, ...rest } = payload state.apps[app] = { ...state.apps[app], ...rest, - }; + } }, }, -}); +}) -export const { toggleGlobalPolling, updatePolling } = slice.actions; +export const { toggleGlobalPolling, updatePolling } = slice.actions -export default slice.reducer; +export default slice.reducer -export const selectGlobalPollingEnabled = (state: RootState) => state.polling.enabled; -export const selectPollingConfigByApp = (state: RootState, app: PollingAppKey) => state.polling.apps[app]; +export const selectGlobalPollingEnabled = (state: RootState) => + state.polling.enabled +export const selectPollingConfigByApp = ( + state: RootState, + app: PollingAppKey, +) => state.polling.apps[app] diff --git a/examples/query/react/kitchen-sink/src/features/time/TimeList.tsx b/examples/query/react/kitchen-sink/src/features/time/TimeList.tsx index 08f3b7f99c..ecca7ca3bf 100644 --- a/examples/query/react/kitchen-sink/src/features/time/TimeList.tsx +++ b/examples/query/react/kitchen-sink/src/features/time/TimeList.tsx @@ -1,10 +1,13 @@ -import * as React from 'react'; -import { nanoid } from '@reduxjs/toolkit'; -import { useEffect } from 'react'; -import { useGetTimeQuery, usePrefetchTime } from '../../app/services/times'; -import { Container } from '../common/Container'; -import { useTypedSelector } from '../../app/store'; -import { selectGlobalPollingEnabled, selectPollingConfigByApp } from '../polling/pollingSlice'; +import * as React from 'react' +import { nanoid } from '@reduxjs/toolkit' +import { useEffect } from 'react' +import { useGetTimeQuery, usePrefetchTime } from '../../app/services/times' +import { Container } from '../common/Container' +import { useTypedSelector } from '../../app/store' +import { + selectGlobalPollingEnabled, + selectPollingConfigByApp, +} from '../polling/pollingSlice' const timezones: Record = { '-12:00': '(GMT -12:00) Eniwetok, Kwajalein', @@ -47,9 +50,13 @@ const timezones: Record = { '+12:75': '(GMT +12:45) Chatham Islands', '+13:00': '(GMT +13:00) Apia, Nukualofa', '+14:00': '(GMT +14:00) Line Islands, Tokelau', -}; +} -const TimeZoneSelector = ({ onChange }: { onChange: (event: React.ChangeEvent) => void }) => { +const TimeZoneSelector = ({ + onChange, +}: { + onChange: (event: React.ChangeEvent) => void +}) => { return ( - ); -}; + ) +} const intervalOptions = [ { label: '0 - Off', value: 0 }, @@ -69,18 +76,20 @@ const intervalOptions = [ { label: '5s', value: 5000 }, { label: '10s', value: 10000 }, { label: '1m', value: 60000 }, -]; +] const TimeDisplay = ({ offset, label }: { offset: string; label: string }) => { - const globalPolling = useTypedSelector(selectGlobalPollingEnabled); - const { enabled: timesPolling } = useTypedSelector((state) => selectPollingConfigByApp(state, 'times')); + const globalPolling = useTypedSelector(selectGlobalPollingEnabled) + const { enabled: timesPolling } = useTypedSelector((state) => + selectPollingConfigByApp(state, 'times'), + ) - const canPoll = globalPolling && timesPolling; + const canPoll = globalPolling && timesPolling - const [pollingInterval, setPollingInterval] = React.useState(0); + const [pollingInterval, setPollingInterval] = React.useState(0) const { data, refetch, isFetching } = useGetTimeQuery(offset, { pollingInterval: canPoll ? pollingInterval : 0, - }); + }) return (
@@ -89,7 +98,12 @@ const TimeDisplay = ({ offset, label }: { offset: string; label: string }) => {

Polling Interval:{' '} - + setPollingInterval(Number(value)) + } + > {intervalOptions.map(({ label, value }) => (

- ); -}; + ) +} export const TimeList = () => { const [times, setTimes] = React.useState<{ [key: string]: string }>({ [nanoid()]: '-08:00', - }); - const [selectedValue, setSelectedValue] = React.useState(''); + }) + const [selectedValue, setSelectedValue] = React.useState('') - const prefetch = usePrefetchTime('getTime'); + const prefetch = usePrefetchTime('getTime') useEffect(() => { setTimeout(() => { - setTimes((prev) => ({ ...prev, [nanoid()]: '+00:00' })); - }, 1000); - }, []); + setTimes((prev) => ({ ...prev, [nanoid()]: '+00:00' })) + }, 1000) + }, []) return ( -

Add some times, even duplicates, and watch them automatically refetch in sync!

+

+ Add some times, even duplicates, and watch them automatically refetch in + sync! +

- Notes: shared queries (aka multiple entries of the same time zone) will share the lowest polling interval - between them that is greater than 0. If all entries are set to 0, it will stop polling. If you have two entries - with a polling time of 5s and one with 0 - off, it will continue at 5s until they are removed or 0'd out. + Notes: shared queries (aka multiple entries of the same time zone) will + share the lowest polling interval between them that is greater than 0. + If all entries are set to 0, it will stop polling. If you have two + entries with a polling time of 5s and one with 0 - off, it will continue + at 5s until they are removed or 0'd out.
- Any new poll starts after the last request has either finished or failed to prevent slow-running requests to - immediately double-trigger. + Any new poll starts after the last request has either finished or failed + to prevent slow-running requests to immediately double-trigger.
* Background flashes green when query is running - +

- setSelectedValue(value)} /> -
@@ -138,5 +166,5 @@ export const TimeList = () => { ))}
- ); -}; + ) +} diff --git a/examples/query/react/kitchen-sink/src/index.tsx b/examples/query/react/kitchen-sink/src/index.tsx index 6df77c3e0a..460d6ad2b6 100644 --- a/examples/query/react/kitchen-sink/src/index.tsx +++ b/examples/query/react/kitchen-sink/src/index.tsx @@ -13,7 +13,7 @@ async function render() { } const rootNode = ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById('root') as HTMLElement, ) rootNode.render( @@ -23,7 +23,7 @@ async function render() { - + , ) } diff --git a/examples/query/react/kitchen-sink/src/mocks/handlers.ts b/examples/query/react/kitchen-sink/src/mocks/handlers.ts index dd5edddee7..5ede1b6f63 100644 --- a/examples/query/react/kitchen-sink/src/mocks/handlers.ts +++ b/examples/query/react/kitchen-sink/src/mocks/handlers.ts @@ -1,113 +1,125 @@ -import { rest } from 'msw'; -import { createEntityAdapter, nanoid } from '@reduxjs/toolkit'; -import { Post } from '../app/services/posts'; +import { rest } from 'msw' +import { createEntityAdapter, nanoid } from '@reduxjs/toolkit' +import { Post } from '../app/services/posts' // We're just going to use a simple in-memory store for both the counter and posts // The entity adapter will handle modifications when triggered by the MSW handlers -let count = 0; -let startingId = 3; // Just a silly counter for usage when adding new posts +let count = 0 +let startingId = 3 // Just a silly counter for usage when adding new posts -const adapter = createEntityAdapter(); +const adapter = createEntityAdapter() -let state = adapter.getInitialState(); +let state = adapter.getInitialState() state = adapter.setAll(state, [ { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() }, - { id: 2, name: 'A post about rtk-query', fetched_at: new Date().toUTCString() }, -]); + { + id: 2, + name: 'A post about rtk-query', + fetched_at: new Date().toUTCString(), + }, +]) -export { state }; +export { state } // Just use a random id for an auth token -const token = nanoid(); +const token = nanoid() export const handlers = [ rest.get('/time/:offset', (req, res, ctx) => { - const { offset } = req.params as { offset: string }; - const date = new Date(); - const localDate = date.getTime(); // users local time - const localOffset = date.getTimezoneOffset() * 60000; - const formattedOffset = Number(offset.replace(':', '.')); - const target = localDate + localOffset + 3600000 * formattedOffset; - return res(ctx.json({ time: new Date(target).toUTCString() }), ctx.delay(400)); + const { offset } = req.params as { offset: string } + const date = new Date() + const localDate = date.getTime() // users local time + const localOffset = date.getTimezoneOffset() * 60000 + const formattedOffset = Number(offset.replace(':', '.')) + const target = localDate + localOffset + 3600000 * formattedOffset + return res( + ctx.json({ time: new Date(target).toUTCString() }), + ctx.delay(400), + ) }), rest.put<{ amount: number }>('/increment', (req, res, ctx) => { - const { amount } = req.body; - count = count += amount; + const { amount } = req.body + count = count += amount - return res(ctx.json({ count })); + return res(ctx.json({ count })) }), rest.put<{ amount: number }>('/decrement', (req, res, ctx) => { - const { amount } = req.body; - count = count -= amount; + const { amount } = req.body + count = count -= amount - return res(ctx.json({ count })); + return res(ctx.json({ count })) }), rest.get('/count', (req, res, ctx) => { - return res(ctx.json({ count })); + return res(ctx.json({ count })) }), rest.post('/login', (req, res, ctx) => { - return res.once(ctx.json({ message: 'i fail once' }), ctx.status(500)); + return res.once(ctx.json({ message: 'i fail once' }), ctx.status(500)) }), rest.post('/login', (req, res, ctx) => { - return res(ctx.json({ token, user: { first_name: 'Test', last_name: 'User' } })); + return res( + ctx.json({ token, user: { first_name: 'Test', last_name: 'User' } }), + ) }), rest.get('/posts', (req, res, ctx) => { - return res(ctx.json(Object.values(state.entities))); + return res(ctx.json(Object.values(state.entities))) }), rest.post('/posts', (req, res, ctx) => { - let post = req.body as Partial; - startingId += 1; - state = adapter.addOne(state, { ...post, id: startingId } as Post); - return res(ctx.json(Object.values(state.entities)), ctx.delay(400)); + let post = req.body as Partial + startingId += 1 + state = adapter.addOne(state, { ...post, id: startingId } as Post) + return res(ctx.json(Object.values(state.entities)), ctx.delay(400)) }), rest.get('/posts/:id', (req, res, ctx) => { const { id: idParam } = req.params as { id: string } const id = parseInt(idParam, 10) - state = adapter.updateOne(state, { id, changes: { fetched_at: new Date().toUTCString() } }); - return res(ctx.json(state.entities[id]), ctx.delay(400)); + state = adapter.updateOne(state, { + id, + changes: { fetched_at: new Date().toUTCString() }, + }) + return res(ctx.json(state.entities[id]), ctx.delay(400)) }), rest.put('/posts/:id', (req, res, ctx) => { const { id: idParam } = req.params as { id: string } const id = parseInt(idParam, 10) - const changes = req.body as Partial; + const changes = req.body as Partial - state = adapter.updateOne(state, { id, changes }); + state = adapter.updateOne(state, { id, changes }) - return res(ctx.json(state.entities[id]), ctx.delay(400)); + return res(ctx.json(state.entities[id]), ctx.delay(400)) }), rest.delete('/posts/:id', (req, res, ctx) => { const { id: idParam } = req.params as { id: string } const id = parseInt(idParam, 10) - state = adapter.removeOne(state, id); + state = adapter.removeOne(state, id) return res( ctx.json({ id, success: true, }), - ctx.delay(600) - ); + ctx.delay(600), + ) }), rest.get('/error-prone', (req, res, ctx) => { if (Math.random() > 0.1) { - return res(ctx.json({ error: 'failed!' }), ctx.status(500)); + return res(ctx.json({ error: 'failed!' }), ctx.status(500)) } return res( ctx.json({ success: true, - }) - ); + }), + ) }), -]; +] diff --git a/examples/query/react/kitchen-sink/src/mocks/setupTests.tsx b/examples/query/react/kitchen-sink/src/mocks/setupTests.tsx index 899d316d61..eee2de33b0 100644 --- a/examples/query/react/kitchen-sink/src/mocks/setupTests.tsx +++ b/examples/query/react/kitchen-sink/src/mocks/setupTests.tsx @@ -24,7 +24,7 @@ export const setupTests = () => { } function renderWithProvider( children: React.ReactChild, - { route, path }: RenderOptions = { route: '/', path: '' } + { route, path }: RenderOptions = { route: '/', path: '' }, ) { const history = createMemoryHistory() history.push(route) @@ -39,7 +39,7 @@ export const setupTests = () => { children )} - + , ) } diff --git a/examples/query/react/kitchen-sink/src/setupTests.ts b/examples/query/react/kitchen-sink/src/setupTests.ts index 74b1a275a0..2eb59b05d8 100644 --- a/examples/query/react/kitchen-sink/src/setupTests.ts +++ b/examples/query/react/kitchen-sink/src/setupTests.ts @@ -2,4 +2,4 @@ // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom -import '@testing-library/jest-dom/extend-expect'; +import '@testing-library/jest-dom/extend-expect' diff --git a/examples/query/react/kitchen-sink/tsconfig.json b/examples/query/react/kitchen-sink/tsconfig.json index d4eea2ea4b..7f331f6806 100644 --- a/examples/query/react/kitchen-sink/tsconfig.json +++ b/examples/query/react/kitchen-sink/tsconfig.json @@ -1,25 +1,20 @@ { - "include": [ - "./src/**/*" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], - "jsx": "react-jsx", - "target": "es5", - "allowJs": true, - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "noFallthroughCasesInSwitch": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true - } -} \ No newline at end of file + "include": ["./src/**/*"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "lib": ["dom", "es2015"], + "jsx": "react-jsx", + "target": "es5", + "allowJs": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + }, +} diff --git a/examples/query/react/mutations/public/index.html b/examples/query/react/mutations/public/index.html index 42ae2d2dcb..efbc007a8b 100644 --- a/examples/query/react/mutations/public/index.html +++ b/examples/query/react/mutations/public/index.html @@ -1,17 +1,19 @@ - + - - - - - - - - - - React App - + React App + - - -
- - - - \ No newline at end of file + + diff --git a/examples/query/react/mutations/src/index.tsx b/examples/query/react/mutations/src/index.tsx index 3854044b5e..ca83c0fe6d 100644 --- a/examples/query/react/mutations/src/index.tsx +++ b/examples/query/react/mutations/src/index.tsx @@ -19,6 +19,6 @@ worker.start({ quiet: true }).then(() => - - ) + , + ), ) diff --git a/examples/query/react/mutations/src/mocks/db.ts b/examples/query/react/mutations/src/mocks/db.ts index 5ade9028d0..98599624e8 100644 --- a/examples/query/react/mutations/src/mocks/db.ts +++ b/examples/query/react/mutations/src/mocks/db.ts @@ -26,7 +26,7 @@ export const handlers = [ return res( ctx.json({ error: 'Oh no, there was an error, try again.' }), ctx.status(500), - ctx.delay(300) + ctx.delay(300), ) } @@ -44,7 +44,7 @@ export const handlers = [ return res( ctx.json({ error: 'Oh no, there was an error, try again.' }), ctx.status(500), - ctx.delay(300) + ctx.delay(300), ) } diff --git a/examples/query/react/mutations/tsconfig.json b/examples/query/react/mutations/tsconfig.json index d4eea2ea4b..7f331f6806 100644 --- a/examples/query/react/mutations/tsconfig.json +++ b/examples/query/react/mutations/tsconfig.json @@ -1,25 +1,20 @@ { - "include": [ - "./src/**/*" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], - "jsx": "react-jsx", - "target": "es5", - "allowJs": true, - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "noFallthroughCasesInSwitch": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true - } -} \ No newline at end of file + "include": ["./src/**/*"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "lib": ["dom", "es2015"], + "jsx": "react-jsx", + "target": "es5", + "allowJs": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + }, +} diff --git a/examples/query/react/optimistic-update/public/index.html b/examples/query/react/optimistic-update/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/optimistic-update/public/index.html +++ b/examples/query/react/optimistic-update/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/optimistic-update/src/app/services/posts.ts b/examples/query/react/optimistic-update/src/app/services/posts.ts index 6fa771dbfe..3033e3ad2f 100644 --- a/examples/query/react/optimistic-update/src/app/services/posts.ts +++ b/examples/query/react/optimistic-update/src/app/services/posts.ts @@ -43,7 +43,7 @@ export const api = createApi({ const patchResult = dispatch( api.util.updateQueryData('getPost', id, (draft) => { Object.assign(draft, patch) - }) + }), ) try { await queryFulfilled diff --git a/examples/query/react/optimistic-update/src/index.tsx b/examples/query/react/optimistic-update/src/index.tsx index 5d044d74eb..9440268a89 100644 --- a/examples/query/react/optimistic-update/src/index.tsx +++ b/examples/query/react/optimistic-update/src/index.tsx @@ -19,6 +19,6 @@ worker.start({ quiet: true }).then(() => - - ) + , + ), ) diff --git a/examples/query/react/optimistic-update/src/mocks/db.ts b/examples/query/react/optimistic-update/src/mocks/db.ts index 73ec3f64a7..98e6857860 100644 --- a/examples/query/react/optimistic-update/src/mocks/db.ts +++ b/examples/query/react/optimistic-update/src/mocks/db.ts @@ -19,7 +19,7 @@ export const handlers = [ return res( ctx.json({ error: 'Oh no, there was an error' }), ctx.status(500), - ctx.delay(400) + ctx.delay(400), ) } diff --git a/examples/query/react/optimistic-update/tsconfig.json b/examples/query/react/optimistic-update/tsconfig.json index 5f488e8e73..7f331f6806 100644 --- a/examples/query/react/optimistic-update/tsconfig.json +++ b/examples/query/react/optimistic-update/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -20,6 +15,6 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "noEmit": true - } + "noEmit": true, + }, } diff --git a/examples/query/react/pagination/public/index.html b/examples/query/react/pagination/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/pagination/public/index.html +++ b/examples/query/react/pagination/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/pagination/src/app/services/posts.ts b/examples/query/react/pagination/src/app/services/posts.ts index 0b50ae3b64..b4863852b2 100644 --- a/examples/query/react/pagination/src/app/services/posts.ts +++ b/examples/query/react/pagination/src/app/services/posts.ts @@ -7,7 +7,7 @@ export interface Post { title: string author: string content: string - status: typeof postStatuses[number] + status: (typeof postStatuses)[number] created_at: string updated_at: string } diff --git a/examples/query/react/pagination/src/features/posts/PostsManager.tsx b/examples/query/react/pagination/src/features/posts/PostsManager.tsx index 9a790c7e9f..52f3b824a9 100644 --- a/examples/query/react/pagination/src/features/posts/PostsManager.tsx +++ b/examples/query/react/pagination/src/features/posts/PostsManager.tsx @@ -23,8 +23,8 @@ const getColorForStatus = (status: Post['status']) => { return status === 'draft' ? 'gray' : status === 'pending_review' - ? 'orange' - : 'green' + ? 'orange' + : 'green' } const PostList = () => { diff --git a/examples/query/react/pagination/src/index.tsx b/examples/query/react/pagination/src/index.tsx index 5d044d74eb..9440268a89 100644 --- a/examples/query/react/pagination/src/index.tsx +++ b/examples/query/react/pagination/src/index.tsx @@ -19,6 +19,6 @@ worker.start({ quiet: true }).then(() => - - ) + , + ), ) diff --git a/examples/query/react/pagination/src/mocks/db.ts b/examples/query/react/pagination/src/mocks/db.ts index 5dc3d0968b..89703a4617 100644 --- a/examples/query/react/pagination/src/mocks/db.ts +++ b/examples/query/react/pagination/src/mocks/db.ts @@ -50,7 +50,7 @@ export const handlers = [ page, total_pages: Math.ceil(db.post.count() / per_page), total: db.post.count(), - }) + }), ) }), ...db.post.toHandlers('rest'), diff --git a/examples/query/react/pagination/tsconfig.json b/examples/query/react/pagination/tsconfig.json index 5f488e8e73..7f331f6806 100644 --- a/examples/query/react/pagination/tsconfig.json +++ b/examples/query/react/pagination/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -20,6 +15,6 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "noEmit": true - } + "noEmit": true, + }, } diff --git a/examples/query/react/polling/public/index.html b/examples/query/react/polling/public/index.html index 42ae2d2dcb..efbc007a8b 100644 --- a/examples/query/react/polling/public/index.html +++ b/examples/query/react/polling/public/index.html @@ -1,17 +1,19 @@ - + - - - - - - - - - - React App - + React App + - - -
- - - - \ No newline at end of file + + diff --git a/examples/query/react/polling/src/Pokemon.tsx b/examples/query/react/polling/src/Pokemon.tsx index 342023c135..e572b83cdd 100644 --- a/examples/query/react/polling/src/Pokemon.tsx +++ b/examples/query/react/polling/src/Pokemon.tsx @@ -15,18 +15,13 @@ const getRandomIntervalValue = () => export const Pokemon = ({ name }: { name: PokemonName }) => { const [pollingInterval, setPollingInterval] = React.useState( - getRandomIntervalValue() + getRandomIntervalValue(), ) - const { - data, - error, - isLoading, - isFetching, - refetch, - } = useGetPokemonByNameQuery(name, { - pollingInterval, - }) + const { data, error, isLoading, isFetching, refetch } = + useGetPokemonByNameQuery(name, { + pollingInterval, + }) return (
- + , ) diff --git a/examples/query/react/polling/src/pokemon.data.ts b/examples/query/react/polling/src/pokemon.data.ts index 1617ce9e50..22eb3a0547 100644 --- a/examples/query/react/polling/src/pokemon.data.ts +++ b/examples/query/react/polling/src/pokemon.data.ts @@ -152,4 +152,4 @@ export const POKEMON_NAMES = [ 'mew', ] as const -export type PokemonName = typeof POKEMON_NAMES[number] +export type PokemonName = (typeof POKEMON_NAMES)[number] diff --git a/examples/query/react/polling/tsconfig.json b/examples/query/react/polling/tsconfig.json index d4eea2ea4b..7f331f6806 100644 --- a/examples/query/react/polling/tsconfig.json +++ b/examples/query/react/polling/tsconfig.json @@ -1,25 +1,20 @@ { - "include": [ - "./src/**/*" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], - "jsx": "react-jsx", - "target": "es5", - "allowJs": true, - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "noFallthroughCasesInSwitch": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true - } -} \ No newline at end of file + "include": ["./src/**/*"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "lib": ["dom", "es2015"], + "jsx": "react-jsx", + "target": "es5", + "allowJs": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + }, +} diff --git a/examples/query/react/prefetching-automatic-waterfall/public/index.html b/examples/query/react/prefetching-automatic-waterfall/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/prefetching-automatic-waterfall/public/index.html +++ b/examples/query/react/prefetching-automatic-waterfall/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/prefetching-automatic-waterfall/src/app/services/posts.ts b/examples/query/react/prefetching-automatic-waterfall/src/app/services/posts.ts index e8cb02f9e4..d4032ef9cf 100644 --- a/examples/query/react/prefetching-automatic-waterfall/src/app/services/posts.ts +++ b/examples/query/react/prefetching-automatic-waterfall/src/app/services/posts.ts @@ -7,7 +7,7 @@ export interface Post { title: string author: string content: string - status: typeof postStatuses[number] + status: (typeof postStatuses)[number] created_at: string updated_at: string } diff --git a/examples/query/react/prefetching-automatic-waterfall/src/features/posts/PostsManager.tsx b/examples/query/react/prefetching-automatic-waterfall/src/features/posts/PostsManager.tsx index e8cea9b348..eb093dade1 100644 --- a/examples/query/react/prefetching-automatic-waterfall/src/features/posts/PostsManager.tsx +++ b/examples/query/react/prefetching-automatic-waterfall/src/features/posts/PostsManager.tsx @@ -23,8 +23,8 @@ const getColorForStatus = (status: Post['status']) => { return status === 'draft' ? 'gray' : status === 'pending_review' - ? 'orange' - : 'green' + ? 'orange' + : 'green' } const PostList = () => { diff --git a/examples/query/react/prefetching-automatic-waterfall/src/index.tsx b/examples/query/react/prefetching-automatic-waterfall/src/index.tsx index 5d044d74eb..9440268a89 100644 --- a/examples/query/react/prefetching-automatic-waterfall/src/index.tsx +++ b/examples/query/react/prefetching-automatic-waterfall/src/index.tsx @@ -19,6 +19,6 @@ worker.start({ quiet: true }).then(() => - - ) + , + ), ) diff --git a/examples/query/react/prefetching-automatic-waterfall/src/mocks/db.ts b/examples/query/react/prefetching-automatic-waterfall/src/mocks/db.ts index 5dc3d0968b..89703a4617 100644 --- a/examples/query/react/prefetching-automatic-waterfall/src/mocks/db.ts +++ b/examples/query/react/prefetching-automatic-waterfall/src/mocks/db.ts @@ -50,7 +50,7 @@ export const handlers = [ page, total_pages: Math.ceil(db.post.count() / per_page), total: db.post.count(), - }) + }), ) }), ...db.post.toHandlers('rest'), diff --git a/examples/query/react/prefetching-automatic-waterfall/tsconfig.json b/examples/query/react/prefetching-automatic-waterfall/tsconfig.json index 5f488e8e73..7f331f6806 100644 --- a/examples/query/react/prefetching-automatic-waterfall/tsconfig.json +++ b/examples/query/react/prefetching-automatic-waterfall/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -20,6 +15,6 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "noEmit": true - } + "noEmit": true, + }, } diff --git a/examples/query/react/prefetching-automatic/public/index.html b/examples/query/react/prefetching-automatic/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/prefetching-automatic/public/index.html +++ b/examples/query/react/prefetching-automatic/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/prefetching-automatic/src/app/services/posts.ts b/examples/query/react/prefetching-automatic/src/app/services/posts.ts index e8cb02f9e4..d4032ef9cf 100644 --- a/examples/query/react/prefetching-automatic/src/app/services/posts.ts +++ b/examples/query/react/prefetching-automatic/src/app/services/posts.ts @@ -7,7 +7,7 @@ export interface Post { title: string author: string content: string - status: typeof postStatuses[number] + status: (typeof postStatuses)[number] created_at: string updated_at: string } diff --git a/examples/query/react/prefetching-automatic/src/features/posts/PostsManager.tsx b/examples/query/react/prefetching-automatic/src/features/posts/PostsManager.tsx index ce01a87daf..3435481082 100644 --- a/examples/query/react/prefetching-automatic/src/features/posts/PostsManager.tsx +++ b/examples/query/react/prefetching-automatic/src/features/posts/PostsManager.tsx @@ -23,8 +23,8 @@ const getColorForStatus = (status: Post['status']) => { return status === 'draft' ? 'gray' : status === 'pending_review' - ? 'orange' - : 'green' + ? 'orange' + : 'green' } const PostList = () => { diff --git a/examples/query/react/prefetching-automatic/src/index.tsx b/examples/query/react/prefetching-automatic/src/index.tsx index 5d044d74eb..9440268a89 100644 --- a/examples/query/react/prefetching-automatic/src/index.tsx +++ b/examples/query/react/prefetching-automatic/src/index.tsx @@ -19,6 +19,6 @@ worker.start({ quiet: true }).then(() => - - ) + , + ), ) diff --git a/examples/query/react/prefetching-automatic/src/mocks/db.ts b/examples/query/react/prefetching-automatic/src/mocks/db.ts index 5dc3d0968b..89703a4617 100644 --- a/examples/query/react/prefetching-automatic/src/mocks/db.ts +++ b/examples/query/react/prefetching-automatic/src/mocks/db.ts @@ -50,7 +50,7 @@ export const handlers = [ page, total_pages: Math.ceil(db.post.count() / per_page), total: db.post.count(), - }) + }), ) }), ...db.post.toHandlers('rest'), diff --git a/examples/query/react/prefetching-automatic/tsconfig.json b/examples/query/react/prefetching-automatic/tsconfig.json index 5f488e8e73..7f331f6806 100644 --- a/examples/query/react/prefetching-automatic/tsconfig.json +++ b/examples/query/react/prefetching-automatic/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -20,6 +15,6 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "noEmit": true - } + "noEmit": true, + }, } diff --git a/examples/query/react/prefetching/public/index.html b/examples/query/react/prefetching/public/index.html index 09e975e218..e65acb3de5 100644 --- a/examples/query/react/prefetching/public/index.html +++ b/examples/query/react/prefetching/public/index.html @@ -1,4 +1,4 @@ - + @@ -41,4 +41,3 @@ --> - diff --git a/examples/query/react/prefetching/src/app/services/posts.ts b/examples/query/react/prefetching/src/app/services/posts.ts index e8cb02f9e4..d4032ef9cf 100644 --- a/examples/query/react/prefetching/src/app/services/posts.ts +++ b/examples/query/react/prefetching/src/app/services/posts.ts @@ -7,7 +7,7 @@ export interface Post { title: string author: string content: string - status: typeof postStatuses[number] + status: (typeof postStatuses)[number] created_at: string updated_at: string } diff --git a/examples/query/react/prefetching/src/features/posts/PostsManager.tsx b/examples/query/react/prefetching/src/features/posts/PostsManager.tsx index 2aaebf2c7c..5999215a98 100644 --- a/examples/query/react/prefetching/src/features/posts/PostsManager.tsx +++ b/examples/query/react/prefetching/src/features/posts/PostsManager.tsx @@ -23,8 +23,8 @@ const getColorForStatus = (status: Post['status']) => { return status === 'draft' ? 'gray' : status === 'pending_review' - ? 'orange' - : 'green' + ? 'orange' + : 'green' } const PostList = () => { diff --git a/examples/query/react/prefetching/src/index.tsx b/examples/query/react/prefetching/src/index.tsx index 5d044d74eb..9440268a89 100644 --- a/examples/query/react/prefetching/src/index.tsx +++ b/examples/query/react/prefetching/src/index.tsx @@ -19,6 +19,6 @@ worker.start({ quiet: true }).then(() => - - ) + , + ), ) diff --git a/examples/query/react/prefetching/src/mocks/db.ts b/examples/query/react/prefetching/src/mocks/db.ts index 5dc3d0968b..89703a4617 100644 --- a/examples/query/react/prefetching/src/mocks/db.ts +++ b/examples/query/react/prefetching/src/mocks/db.ts @@ -50,7 +50,7 @@ export const handlers = [ page, total_pages: Math.ceil(db.post.count() / per_page), total: db.post.count(), - }) + }), ) }), ...db.post.toHandlers('rest'), diff --git a/examples/query/react/prefetching/tsconfig.json b/examples/query/react/prefetching/tsconfig.json index 5f488e8e73..7f331f6806 100644 --- a/examples/query/react/prefetching/tsconfig.json +++ b/examples/query/react/prefetching/tsconfig.json @@ -1,14 +1,9 @@ { - "include": [ - "./src/**/*" - ], + "include": ["./src/**/*"], "compilerOptions": { "strict": true, "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], + "lib": ["dom", "es2015"], "jsx": "react-jsx", "target": "es5", "allowJs": true, @@ -20,6 +15,6 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "noEmit": true - } + "noEmit": true, + }, } diff --git a/examples/query/react/with-apiprovider/public/index.html b/examples/query/react/with-apiprovider/public/index.html index 42ae2d2dcb..efbc007a8b 100644 --- a/examples/query/react/with-apiprovider/public/index.html +++ b/examples/query/react/with-apiprovider/public/index.html @@ -1,17 +1,19 @@ - + - - - - - - - - - - React App - + React App + - - -
- - - - \ No newline at end of file + + diff --git a/examples/query/react/with-apiprovider/src/App.tsx b/examples/query/react/with-apiprovider/src/App.tsx index a91982c4b9..f8ded9f1b6 100644 --- a/examples/query/react/with-apiprovider/src/App.tsx +++ b/examples/query/react/with-apiprovider/src/App.tsx @@ -14,9 +14,8 @@ const api = createApi({ }) function Pokemon() { - const { data, refetch, isFetching } = api.useGetPokemonByNameQuery( - 'bulbasaur' - ) + const { data, refetch, isFetching } = + api.useGetPokemonByNameQuery('bulbasaur') return (
diff --git a/examples/query/react/with-apiprovider/tsconfig.json b/examples/query/react/with-apiprovider/tsconfig.json index d4eea2ea4b..7f331f6806 100644 --- a/examples/query/react/with-apiprovider/tsconfig.json +++ b/examples/query/react/with-apiprovider/tsconfig.json @@ -1,25 +1,20 @@ { - "include": [ - "./src/**/*" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "lib": [ - "dom", - "es2015" - ], - "jsx": "react-jsx", - "target": "es5", - "allowJs": true, - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "noFallthroughCasesInSwitch": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true - } -} \ No newline at end of file + "include": ["./src/**/*"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "lib": ["dom", "es2015"], + "jsx": "react-jsx", + "target": "es5", + "allowJs": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + }, +} diff --git a/packages/rtk-codemods/.github/workflows/ci.yml b/packages/rtk-codemods/.github/workflows/ci.yml index ec853b3887..a4dd4e2ed0 100644 --- a/packages/rtk-codemods/.github/workflows/ci.yml +++ b/packages/rtk-codemods/.github/workflows/ci.yml @@ -10,7 +10,7 @@ on: - '*' pull_request: {} schedule: - - cron: '0 6 * * 0' # weekly, on sundays + - cron: '0 6 * * 0' # weekly, on sundays jobs: lint: @@ -18,14 +18,14 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - uses: actions/setup-node@v1 - with: - node-version: 12.x - - name: install dependencies - run: yarn install --frozen-lockfile - - name: linting - run: yarn lint + - uses: actions/checkout@v1 + - uses: actions/setup-node@v1 + with: + node-version: 12.x + - name: install dependencies + run: yarn install --frozen-lockfile + - name: linting + run: yarn lint test: name: Tests @@ -36,25 +36,25 @@ jobs: node: ['10', '12', '14'] steps: - - uses: actions/checkout@v1 - - uses: actions/setup-node@v1 - with: - node-version: ${{ matrix.node }} - - name: install dependencies - run: yarn install --frozen-lockfile - - name: test - run: yarn test + - uses: actions/checkout@v1 + - uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node }} + - name: install dependencies + run: yarn install --frozen-lockfile + - name: test + run: yarn test floating-test: name: Floating dependencies runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - uses: actions/setup-node@v1 - with: - node-version: '12.x' - - name: install dependencies - run: yarn install --no-lockfile - - name: test - run: yarn test \ No newline at end of file + - uses: actions/checkout@v1 + - uses: actions/setup-node@v1 + with: + node-version: '12.x' + - name: install dependencies + run: yarn install --no-lockfile + - name: test + run: yarn test diff --git a/packages/rtk-codemods/transforms/createReducerBuilder/README.md b/packages/rtk-codemods/transforms/createReducerBuilder/README.md index 52898146e9..1c91761f45 100644 --- a/packages/rtk-codemods/transforms/createReducerBuilder/README.md +++ b/packages/rtk-codemods/transforms/createReducerBuilder/README.md @@ -39,30 +39,36 @@ node ./bin/cli.js createReducerBuilder path/of/files/ or/some**/*glob.js createReducer(initialState, { [todoAdded]: (state: SliceState, action: PayloadAction) => { // stuff - }, -}); + } +}) createReducer(initialState, { [todoAdded](state: SliceState, action: PayloadAction) { // stuff - }, -}); + } +}) ``` **Output** ([basic-ts.output.ts](transforms\createReducerBuilder__testfixtures__\basic-ts.output.ts)): ```ts createReducer(initialState, (builder) => { - builder.addCase(todoAdded, (state: SliceState, action: PayloadAction) => { - // stuff - }); -}); + builder.addCase( + todoAdded, + (state: SliceState, action: PayloadAction) => { + // stuff + } + ) +}) createReducer(initialState, (builder) => { - builder.addCase(todoAdded, (state: SliceState, action: PayloadAction) => { - // stuff - }); -}); + builder.addCase( + todoAdded, + (state: SliceState, action: PayloadAction) => { + // stuff + } + ) +}) ``` --- @@ -88,8 +94,8 @@ createReducer(initialState, { }, todoAdded1f: (state, action) => { //stuff - }, -}); + } +}) createReducer(initialState, { [todoAdded2a]: (state, action) => { @@ -100,8 +106,8 @@ createReducer(initialState, { }, [todoAdded2c]: function (state, action) { // stuff - }, -}); + } +}) ``` **Output** ([basic.output.js](transforms\createReducerBuilder__testfixtures__\basic.output.js)): @@ -110,40 +116,40 @@ createReducer(initialState, { createReducer(initialState, (builder) => { builder.addCase(todoAdded1a, (state, action) => { // stuff - }); + }) - builder.addCase(todoAdded1b, (state, action) => action.payload); + builder.addCase(todoAdded1b, (state, action) => action.payload) builder.addCase(todoAdded1c + 'test', (state, action) => { // stuff - }); + }) builder.addCase(todoAdded1d, (state, action) => { // stuff - }); + }) builder.addCase(todoAdded1e, (state, action) => { // stuff - }); + }) builder.addCase(todoAdded1f, (state, action) => { //stuff - }); -}); + }) +}) createReducer(initialState, (builder) => { builder.addCase(todoAdded2a, (state, action) => { // stuff - }); + }) builder.addCase(todoAdded2b, (state, action) => { // stuff - }); + }) builder.addCase(todoAdded2c, (state, action) => { // stuff - }); -}); + }) +}) ``` diff --git a/packages/rtk-codemods/transforms/createSliceBuilder/README.md b/packages/rtk-codemods/transforms/createSliceBuilder/README.md index 5a15c86682..1db6f8f6de 100644 --- a/packages/rtk-codemods/transforms/createSliceBuilder/README.md +++ b/packages/rtk-codemods/transforms/createSliceBuilder/README.md @@ -42,9 +42,9 @@ const slice1 = createSlice({ extraReducers: { [todoAdded]: (state: SliceState, action: PayloadAction) => { // stuff - }, - }, -}); + } + } +}) const slice2 = createSlice({ name: 'b', @@ -52,9 +52,9 @@ const slice2 = createSlice({ extraReducers: { [todoAdded](state: SliceState, action: PayloadAction) { // stuff - }, - }, -}); + } + } +}) ``` **Output** ([basic-ts.output.ts](transforms\createSliceBuilder__testfixtures__\basic-ts.output.ts)): @@ -65,22 +65,28 @@ const slice1 = createSlice({ initialState, extraReducers: (builder) => { - builder.addCase(todoAdded, (state: SliceState, action: PayloadAction) => { - // stuff - }); - }, -}); + builder.addCase( + todoAdded, + (state: SliceState, action: PayloadAction) => { + // stuff + } + ) + } +}) const slice2 = createSlice({ name: 'b', initialState, extraReducers: (builder) => { - builder.addCase(todoAdded, (state: SliceState, action: PayloadAction) => { - // stuff - }); - }, -}); + builder.addCase( + todoAdded, + (state: SliceState, action: PayloadAction) => { + // stuff + } + ) + } +}) ``` --- @@ -109,9 +115,9 @@ const slice1 = createSlice({ }, todoAdded1f: (state, action) => { //stuff - }, - }, -}); + } + } +}) const slice2 = createSlice({ name: 'b', @@ -125,9 +131,9 @@ const slice2 = createSlice({ }, [todoAdded2c]: function (state, action) { // stuff - }, - }, -}); + } + } +}) ``` **Output** ([basic.output.js](transforms\createSliceBuilder__testfixtures__\basic.output.js)): @@ -140,27 +146,27 @@ const slice1 = createSlice({ extraReducers: (builder) => { builder.addCase(todoAdded1a, (state, action) => { // stuff - }); + }) - builder.addCase(todoAdded1b, (state, action) => action.payload); + builder.addCase(todoAdded1b, (state, action) => action.payload) builder.addCase(todoAdded1c + 'test', (state, action) => { // stuff - }); + }) builder.addCase(todoAdded1d, (state, action) => { // stuff - }); + }) builder.addCase(todoAdded1e, (state, action) => { // stuff - }); + }) builder.addCase(todoAdded1f, (state, action) => { //stuff - }); - }, -}); + }) + } +}) const slice2 = createSlice({ name: 'b', @@ -169,17 +175,17 @@ const slice2 = createSlice({ extraReducers: (builder) => { builder.addCase(todoAdded2a, (state, action) => { // stuff - }); + }) builder.addCase(todoAdded2b, (state, action) => { // stuff - }); + }) builder.addCase(todoAdded2c, (state, action) => { // stuff - }); - }, -}); + }) + } +}) ``` diff --git a/packages/rtk-query-codegen-openapi/ChangeLog.md b/packages/rtk-query-codegen-openapi/ChangeLog.md index b4dffc2183..8e1b25535c 100644 --- a/packages/rtk-query-codegen-openapi/ChangeLog.md +++ b/packages/rtk-query-codegen-openapi/ChangeLog.md @@ -11,24 +11,28 @@ This version adds a new `mergeReadWriteOnly` configuration option (default to `f ## 1.1.3 - 2023-10-11 ### Added + - Adds a temporary workaround for [4.9.0 and 4.10.0 generate circular types oazapfts/oazapfts#491](https://github.com/oazapfts/oazapfts/issues/491) ## 1.1.2 - 2023-10-11 ### Added -- Support for Read Only Properties in the Open API spec. Previously, this property was ignored. + +- Support for Read Only Properties in the Open API spec. Previously, this property was ignored. - Now if the readOnly property is present and set to `true` in a schema, it will split the type into two types: one with the read only property suffixed as 'Read' and the other without the read only properties, using the same type name as before. - This may cause issues if you had your OpenAPI spec properly typed/configured, as it will remove the read onyl types from your existing type. You will need to switch to the new type suffixed as 'Read' to avoid missing property names. -## 1.1.1 - 2023-10-11 +## 1.1.1 - 2023-10-11 ### Changed + - Codegen: better handling of duplicate param names ([Codegen: better handling of duplicate param names #3780](https://github.com/reduxjs/redux-toolkit/pull/3780)) - If a parameter name is both used in a query and a parameter, it will be prefixed with `query`/`param` now to avoid conflicts -## 1.1.0 - 2023-10-11 +## 1.1.0 - 2023-10-11 ### Added + - Option of generating real TS enums instead of string unions [Adds the option of generating real TS enums instead of string unions #2854](https://github.com/reduxjs/redux-toolkit/pull/2854) - Compatibility with TypeScript 5.x versions as the codegen relies on the TypeScript AST for code generation - As a result also needs a higher TypeScript version to work with (old version range was 4.1-4.5) diff --git a/packages/rtk-query-codegen-openapi/src/generate.ts b/packages/rtk-query-codegen-openapi/src/generate.ts index 6e26697ac1..9c5c00c158 100644 --- a/packages/rtk-query-codegen-openapi/src/generate.ts +++ b/packages/rtk-query-codegen-openapi/src/generate.ts @@ -175,13 +175,13 @@ export async function generateApi( ...apiGen.enumAliases, ...(hooks ? [ - generateReactHooks({ - exportName: generatedApiName, - operationDefinitions, - endpointOverrides, - config: hooks, - }), - ] + generateReactHooks({ + exportName: generatedApiName, + operationDefinitions, + endpointOverrides, + config: hooks, + }), + ] : []), ], factory.createToken(ts.SyntaxKind.EndOfFileToken), @@ -301,7 +301,9 @@ export async function generateApi( const body = apiGen.resolve(requestBody); const schema = apiGen.getSchemaFromContent(body.content); const type = apiGen.getTypeFromSchema(schema); - const schemaName = camelCase((type as any).name || getReferenceName(schema) || ("title" in schema && schema.title) || 'body'); + const schemaName = camelCase( + (type as any).name || getReferenceName(schema) || ('title' in schema && schema.title) || 'body' + ); const name = generateName(schemaName in queryArg ? 'body' : schemaName, 'body'); queryArg[name] = { @@ -335,19 +337,19 @@ export async function generateApi( ? isFlatArg ? withQueryComment({ ...queryArgValues[0].type }, queryArgValues[0], false) : factory.createTypeLiteralNode( - queryArgValues.map((def) => - withQueryComment( - factory.createPropertySignature( - undefined, - propertyName(def.name), - createQuestionToken(!def.required), - def.type - ), - def, - true + queryArgValues.map((def) => + withQueryComment( + factory.createPropertySignature( + undefined, + propertyName(def.name), + createQuestionToken(!def.required), + def.type + ), + def, + true + ) ) ) - ) : factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword) ) ).name @@ -391,18 +393,18 @@ export async function generateApi( return parameters.length === 0 ? undefined : factory.createPropertyAssignment( - factory.createIdentifier(propertyName), - factory.createObjectLiteralExpression( - parameters.map( - (param) => - createPropertyAssignment( - param.originalName, - isFlatArg ? rootObject : accessProperty(rootObject, param.name) - ), - true + factory.createIdentifier(propertyName), + factory.createObjectLiteralExpression( + parameters.map( + (param) => + createPropertyAssignment( + param.originalName, + isFlatArg ? rootObject : accessProperty(rootObject, param.name) + ), + true + ) ) - ) - ); + ); } return factory.createArrowFunction( @@ -423,17 +425,17 @@ export async function generateApi( isQuery && verb.toUpperCase() === 'GET' ? undefined : factory.createPropertyAssignment( - factory.createIdentifier('method'), - factory.createStringLiteral(verb.toUpperCase()) - ), + factory.createIdentifier('method'), + factory.createStringLiteral(verb.toUpperCase()) + ), bodyParameter === undefined ? undefined : factory.createPropertyAssignment( - factory.createIdentifier('body'), - isFlatArg - ? rootObject - : factory.createPropertyAccessExpression(rootObject, factory.createIdentifier(bodyParameter.name)) - ), + factory.createIdentifier('body'), + isFlatArg + ? rootObject + : factory.createPropertyAccessExpression(rootObject, factory.createIdentifier(bodyParameter.name)) + ), createObjectLiteralProperty(pickParams('cookie'), 'cookies'), createObjectLiteralProperty(pickParams('header'), 'headers'), createObjectLiteralProperty(pickParams('query'), 'params'), @@ -445,12 +447,12 @@ export async function generateApi( } // eslint-disable-next-line no-empty-pattern - function generateQueryEndpointProps({ }: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions { + function generateQueryEndpointProps({}: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions { return {}; /* TODO needs implementation - skip for now */ } // eslint-disable-next-line no-empty-pattern - function generateMutationEndpointProps({ }: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions { + function generateMutationEndpointProps({}: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions { return {}; /* TODO needs implementation - skip for now */ } } @@ -480,16 +482,16 @@ function generatePathExpression( return expressions.length ? factory.createTemplateExpression( - factory.createTemplateHead(head), - expressions.map(([prop, literal], index) => - factory.createTemplateSpan( - isFlatArg ? rootObject : accessProperty(rootObject, prop), - index === expressions.length - 1 - ? factory.createTemplateTail(literal) - : factory.createTemplateMiddle(literal) + factory.createTemplateHead(head), + expressions.map(([prop, literal], index) => + factory.createTemplateSpan( + isFlatArg ? rootObject : accessProperty(rootObject, prop), + index === expressions.length - 1 + ? factory.createTemplateTail(literal) + : factory.createTemplateMiddle(literal) + ) ) ) - ) : factory.createNoSubstitutionTemplateLiteral(head); } @@ -500,13 +502,13 @@ type QueryArgDefinition = { required?: boolean; param?: OpenAPIV3.ParameterObject; } & ( - | { + | { origin: 'param'; param: OpenAPIV3.ParameterObject; } - | { + | { origin: 'body'; body: OpenAPIV3.RequestBodyObject; } - ); +); type QueryArgDefinitions = Record; diff --git a/packages/rtk-query-codegen-openapi/src/types.ts b/packages/rtk-query-codegen-openapi/src/types.ts index bc6fba5d74..701060a6bf 100644 --- a/packages/rtk-query-codegen-openapi/src/types.ts +++ b/packages/rtk-query-codegen-openapi/src/types.ts @@ -2,7 +2,7 @@ import type { OpenAPIV3 } from 'openapi-types'; export type OperationDefinition = { path: string; - verb: typeof operationKeys[number]; + verb: (typeof operationKeys)[number]; pathItem: OpenAPIV3.PathItemObject; operation: OpenAPIV3.OperationObject; }; diff --git a/packages/rtk-query-codegen-openapi/src/utils/getOperationDefinitions.ts b/packages/rtk-query-codegen-openapi/src/utils/getOperationDefinitions.ts index 5cd3854d28..16f1a6f3e7 100644 --- a/packages/rtk-query-codegen-openapi/src/utils/getOperationDefinitions.ts +++ b/packages/rtk-query-codegen-openapi/src/utils/getOperationDefinitions.ts @@ -7,7 +7,7 @@ export function getOperationDefinitions(v3Doc: OpenAPIV3.Document): OperationDef !pathItem ? [] : Object.entries(pathItem) - .filter((arg): arg is [typeof operationKeys[number], OpenAPIV3.OperationObject] => + .filter((arg): arg is [(typeof operationKeys)[number], OpenAPIV3.OperationObject] => operationKeys.includes(arg[0] as any) ) .map(([verb, operation]) => ({ diff --git a/packages/rtk-query-codegen-openapi/src/utils/isQuery.ts b/packages/rtk-query-codegen-openapi/src/utils/isQuery.ts index 8bb779ce17..2cf756e676 100644 --- a/packages/rtk-query-codegen-openapi/src/utils/isQuery.ts +++ b/packages/rtk-query-codegen-openapi/src/utils/isQuery.ts @@ -1,6 +1,6 @@ import type { EndpointOverrides, operationKeys } from '../types'; -export function isQuery(verb: typeof operationKeys[number], overrides: EndpointOverrides | undefined) { +export function isQuery(verb: (typeof operationKeys)[number], overrides: EndpointOverrides | undefined) { if (overrides?.type) { return overrides.type === 'query'; } diff --git a/packages/rtk-query-codegen-openapi/test/generateEndpoints.test.ts b/packages/rtk-query-codegen-openapi/test/generateEndpoints.test.ts index 8171f0ca6f..d922e7ff55 100644 --- a/packages/rtk-query-codegen-openapi/test/generateEndpoints.test.ts +++ b/packages/rtk-query-codegen-openapi/test/generateEndpoints.test.ts @@ -379,7 +379,7 @@ describe('openapi spec', () => { unionUndefined: true, schemaFile: './fixtures/readOnlyWriteOnly.yaml', apiFile: './fixtures/emptyApi.ts', - mergeReadWriteOnly: true + mergeReadWriteOnly: true, }); expect(api).toMatchSnapshot(); }); diff --git a/packages/rtk-query-codegen-openapi/test/tsconfig.json b/packages/rtk-query-codegen-openapi/test/tsconfig.json index 499c1c5631..1c8d5b68ec 100644 --- a/packages/rtk-query-codegen-openapi/test/tsconfig.json +++ b/packages/rtk-query-codegen-openapi/test/tsconfig.json @@ -3,7 +3,7 @@ "lib": ["es2019"], "paths": { "@/*": ["./test/fixtures/*"], - "@rtk-query/codegen-openapi": ["./src"] + "@rtk-query/codegen-openapi": ["./src"], }, "allowSyntheticDefaultImports": true, "esModuleInterop": true, @@ -17,6 +17,6 @@ "resolveJsonModule": true, "types": ["node", "jest"], "allowJs": true, - "checkJs": true - } + "checkJs": true, + }, } diff --git a/packages/rtk-query-codegen-openapi/tsconfig.json b/packages/rtk-query-codegen-openapi/tsconfig.json index 28cad6ed33..6527f11b9d 100644 --- a/packages/rtk-query-codegen-openapi/tsconfig.json +++ b/packages/rtk-query-codegen-openapi/tsconfig.json @@ -66,7 +66,7 @@ /* Advanced Options */ "skipLibCheck": true /* Skip type checking of declaration files. */, - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */, }, - "exclude": ["test", "lib"] + "exclude": ["test", "lib"], } diff --git a/packages/rtk-query-graphql-request-base-query/src/GraphqlBaseQueryTypes.ts b/packages/rtk-query-graphql-request-base-query/src/GraphqlBaseQueryTypes.ts index 0c34984567..562d85ae32 100644 --- a/packages/rtk-query-graphql-request-base-query/src/GraphqlBaseQueryTypes.ts +++ b/packages/rtk-query-graphql-request-base-query/src/GraphqlBaseQueryTypes.ts @@ -3,21 +3,24 @@ import type { GraphQLClient, RequestOptions, RequestDocument, - ClientError + ClientError, } from 'graphql-request' export type Document = RequestDocument export type RequestHeaders = RequestOptions['requestHeaders'] export type PrepareHeaders = ( headers: Headers, - api: Pick + api: Pick< + BaseQueryApi, + 'getState' | 'endpoint' | 'type' | 'forced' | 'extra' + >, ) => MaybePromise export type ErrorResponse = { - message: string; - stack: string; - name: string; -}; + message: string + stack: string + name: string +} export type GraphqlRequestBaseQueryArgs = ( | { @@ -26,8 +29,8 @@ export type GraphqlRequestBaseQueryArgs = ( | { client: GraphQLClient } ) & { requestHeaders?: RequestHeaders - prepareHeaders?: PrepareHeaders, - customErrors?: (args: ClientError) => E; + prepareHeaders?: PrepareHeaders + customErrors?: (args: ClientError) => E } export type QueryReturnValue = diff --git a/packages/rtk-query-graphql-request-base-query/src/index.ts b/packages/rtk-query-graphql-request-base-query/src/index.ts index 481ed629ac..b796c5d6d8 100644 --- a/packages/rtk-query-graphql-request-base-query/src/index.ts +++ b/packages/rtk-query-graphql-request-base-query/src/index.ts @@ -10,7 +10,7 @@ import type { } from './GraphqlBaseQueryTypes' export const graphqlRequestBaseQuery = ( - options: GraphqlRequestBaseQueryArgs + options: GraphqlRequestBaseQueryArgs, ): BaseQueryFn< { document: string | DocumentNode; variables?: any }, unknown, @@ -24,7 +24,7 @@ export const graphqlRequestBaseQuery = ( return async ( { document, variables }, - { getState, endpoint, forced, type, signal, extra } + { getState, endpoint, forced, type, signal, extra }, ) => { try { const prepareHeaders: PrepareHeaders = diff --git a/packages/rtk-query-graphql-request-base-query/tsconfig.json b/packages/rtk-query-graphql-request-base-query/tsconfig.json index 98694b0257..076aee3602 100644 --- a/packages/rtk-query-graphql-request-base-query/tsconfig.json +++ b/packages/rtk-query-graphql-request-base-query/tsconfig.json @@ -4,8 +4,8 @@ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */, + "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ @@ -25,7 +25,7 @@ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ @@ -51,7 +51,7 @@ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ @@ -66,10 +66,8 @@ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + "skipLibCheck": true /* Skip type checking of declaration files. */, + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */, }, - "include": [ - "**/*.ts" - ] + "include": ["**/*.ts"], } diff --git a/packages/toolkit/.size-limit.js b/packages/toolkit/.size-limit.js index 70f8386b54..f53d057bea 100644 --- a/packages/toolkit/.size-limit.js +++ b/packages/toolkit/.size-limit.js @@ -8,15 +8,15 @@ function withRtkPath(suffix) { config.plugins.push( new webpack.NormalModuleReplacementPlugin( /@reduxjs\/toolkit\/query\/react/, - join(__dirname, `query/react`) + join(__dirname, `query/react`), ), new webpack.NormalModuleReplacementPlugin( /@reduxjs\/toolkit\/query/, - join(__dirname, `query`) + join(__dirname, `query`), ), new webpack.NormalModuleReplacementPlugin( /@reduxjs\/toolkit/, - join(__dirname) + join(__dirname), ), new webpack.NormalModuleReplacementPlugin( /rtk-query-react.modern.js/, @@ -24,16 +24,16 @@ function withRtkPath(suffix) { const old = r.request r.request = r.request.replace( /rtk-query-react.modern.js$/, - `rtk-query-react.${suffix}` + `rtk-query-react.${suffix}`, ) // console.log(old, '=>', r.request) - } + }, ), new webpack.NormalModuleReplacementPlugin(/rtk-query.modern.js/, (r) => { const old = r.request r.request = r.request.replace( /rtk-query.modern.js$/, - `rtk-query.${suffix}` + `rtk-query.${suffix}`, ) // console.log(old, '=>', r.request) }), @@ -43,11 +43,11 @@ function withRtkPath(suffix) { const old = r.request r.request = r.request.replace( /redux-toolkit.modern.js$/, - `redux-toolkit.${suffix}` + `redux-toolkit.${suffix}`, ) // console.log(old, '=>', r.request) - } - ) + }, + ), ) if (suffix === 'cjs.production.min.js') { config.resolve.mainFields = ['main', 'module'] @@ -100,7 +100,7 @@ module.exports = [ ...e, name: e.name + ` (${suffix})`, modifyWebpackConfig: withRtkPath(suffix), - })) + })), ) .concat( ...[ @@ -140,5 +140,5 @@ module.exports = [ ...e, name: e.name + ` (esm.js)`, modifyWebpackConfig: withRtkPath('esm.js'), - })) + })), ) diff --git a/packages/toolkit/etc/redux-toolkit.api.md b/packages/toolkit/etc/redux-toolkit.api.md index 8628682b33..dcfe7462b0 100644 --- a/packages/toolkit/etc/redux-toolkit.api.md +++ b/packages/toolkit/etc/redux-toolkit.api.md @@ -31,7 +31,7 @@ import type { ThunkMiddleware } from 'redux-thunk' // @public export interface ActionCreatorWithNonInferrablePayload< - T extends string = string + T extends string = string, > extends BaseActionCreator { (payload: PT): PayloadAction } @@ -60,35 +60,35 @@ export interface ActionCreatorWithPreparedPayload< P, T extends string = string, E = never, - M = never + M = never, > extends BaseActionCreator { (...args: Args): PayloadAction } // @public (undocumented) export type ActionMatchingAllOf< - Matchers extends [Matcher, ...Matcher[]] + Matchers extends [Matcher, ...Matcher[]], > = UnionToIntersection> // @public (undocumented) export type ActionMatchingAnyOf< - Matchers extends [Matcher, ...Matcher[]] + Matchers extends [Matcher, ...Matcher[]], > = ActionFromMatcher // @public export interface ActionReducerMapBuilder { addCase>( actionCreator: ActionCreator, - reducer: CaseReducer> + reducer: CaseReducer>, ): ActionReducerMapBuilder addCase>( type: Type, - reducer: CaseReducer + reducer: CaseReducer, ): ActionReducerMapBuilder addDefaultCase(reducer: CaseReducer): {} addMatcher( matcher: TypeGuard | ((action: any) => boolean), - reducer: CaseReducer + reducer: CaseReducer, ): Omit, 'addCase'> } @@ -99,7 +99,7 @@ export type Actions = Record export type AsyncThunk< Returned, ThunkArg, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, > = AsyncThunkActionCreator & { pending: AsyncThunkPendingActionCreator rejected: AsyncThunkRejectedActionCreator @@ -115,11 +115,11 @@ export type AsyncThunk< export type AsyncThunkAction< Returned, ThunkArg, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, > = ( dispatch: GetDispatch, getState: () => GetState, - extra: GetExtra + extra: GetExtra, ) => Promise< | ReturnType> | ReturnType> @@ -133,11 +133,11 @@ export type AsyncThunkAction< // @public export type AsyncThunkOptions< ThunkArg = void, - ThunkApiConfig extends AsyncThunkConfig = {} + ThunkApiConfig extends AsyncThunkConfig = {}, > = { condition?( arg: ThunkArg, - api: Pick, 'getState' | 'extra'> + api: Pick, 'getState' | 'extra'>, ): MaybePromise dispatchConditionRejection?: boolean serializeError?: (x: unknown) => GetSerializedErrorType @@ -150,7 +150,7 @@ export type AsyncThunkOptions< arg: ThunkArg requestId: string }, - api: Pick, 'getState' | 'extra'> + api: Pick, 'getState' | 'extra'>, ): GetPendingMeta }, { @@ -159,7 +159,7 @@ export type AsyncThunkOptions< arg: ThunkArg requestId: string }, - api: Pick, 'getState' | 'extra'> + api: Pick, 'getState' | 'extra'>, ): GetPendingMeta } > @@ -168,16 +168,16 @@ export type AsyncThunkOptions< export type AsyncThunkPayloadCreator< Returned, ThunkArg = void, - ThunkApiConfig extends AsyncThunkConfig = {} + ThunkApiConfig extends AsyncThunkConfig = {}, > = ( arg: ThunkArg, - thunkAPI: GetThunkAPI + thunkAPI: GetThunkAPI, ) => AsyncThunkPayloadCreatorReturnValue // @public export type AsyncThunkPayloadCreatorReturnValue< Returned, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, > = MaybePromise< | IsUnknown< GetFulfilledMeta, @@ -193,7 +193,7 @@ export type AsyncThunkPayloadCreatorReturnValue< // @public export type CaseReducer = ( state: Draft, - action: A + action: A, ) => S | void | Draft // @public @@ -221,21 +221,21 @@ export type Comparer = (a: T, b: T) => number // @public export type ConfigureEnhancersCallback = ( - defaultEnhancers: readonly StoreEnhancer[] + defaultEnhancers: readonly StoreEnhancer[], ) => StoreEnhancer[] // @public export function configureStore< S = any, A extends Action = UnknownAction, - M extends Middlewares = [ThunkMiddlewareFor] + M extends Middlewares = [ThunkMiddlewareFor], >(options: ConfigureStoreOptions): EnhancedStore // @public export interface ConfigureStoreOptions< S = any, A extends Action = UnknownAction, - M extends Middlewares = Middlewares + M extends Middlewares = Middlewares, > { devTools?: boolean | EnhancerOptions enhancers?: StoreEnhancer[] | ConfigureEnhancersCallback @@ -246,34 +246,34 @@ export interface ConfigureStoreOptions< // @public export function createAction

| void = void + PA extends PrepareAction

| void = void, > = IfPrepareActionMethodProvided< PA, _ActionCreatorWithPreparedPayload, @@ -786,7 +786,7 @@ export interface SerializedError { export interface Slice< State = any, CaseReducers extends SliceCaseReducers = SliceCaseReducers, - Name extends string = string + Name extends string = string, > { actions: CaseReducerActions caseReducers: SliceDefinedCaseReducers @@ -811,7 +811,7 @@ export { ThunkDispatch } // @public (undocumented) export function unwrapResult( - action: R + action: R, ): UnwrappedActionPayload // @public (undocumented) @@ -823,17 +823,16 @@ export type Update = { // @public export type ValidateSliceCaseReducers< S, - ACR extends SliceCaseReducers -> = ACR & - { - [T in keyof ACR]: ACR[T] extends { - reducer(s: S, action?: infer A): any - } - ? { - prepare(...a: never[]): Omit - } - : {} + ACR extends SliceCaseReducers, +> = ACR & { + [T in keyof ACR]: ACR[T] extends { + reducer(s: S, action?: infer A): any } + ? { + prepare(...a: never[]): Omit + } + : {} +} export * from 'redux' diff --git a/packages/toolkit/etc/rtk-query-react.api.md b/packages/toolkit/etc/rtk-query-react.api.md index a4e1079965..d50f544427 100644 --- a/packages/toolkit/etc/rtk-query-react.api.md +++ b/packages/toolkit/etc/rtk-query-react.api.md @@ -18,7 +18,7 @@ export type Api< Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string, - Enhancers extends ModuleName = CoreModule + Enhancers extends ModuleName = CoreModule, > = Id< Id< UnionToIntersection< @@ -27,7 +27,7 @@ export type Api< > & { injectEndpoints(_: { endpoints: ( - build: EndpointBuilder + build: EndpointBuilder, ) => NewDefinitions overrideExisting?: boolean }): Api< @@ -64,7 +64,7 @@ export interface ApiModules< BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, > {} // @public @@ -80,7 +80,7 @@ export type ApiWithInjectedEndpoints< ApiDefinition extends Api, Injections extends ApiDefinition extends Api ? [Api, ...Api[]] - : never + : never, > = Omit & Omit & { endpoints: ApiDefinition['endpoints'] & @@ -91,10 +91,10 @@ export type ApiWithInjectedEndpoints< export type BaseQueryEnhancer< AdditionalArgs = unknown, AdditionalDefinitionExtraOptions = unknown, - Config = void + Config = void, > = ( baseQuery: BaseQuery, - config: Config + config: Config, ) => BaseQueryFn< BaseQueryArg & AdditionalArgs, BaseQueryResult, @@ -108,11 +108,11 @@ export type BaseQueryFn< Result = unknown, Error = unknown, DefinitionExtraOptions = {}, - Meta = {} + Meta = {}, > = ( args: Args, api: BaseQueryApi, - extraOptions: DefinitionExtraOptions + extraOptions: DefinitionExtraOptions, ) => MaybePromise> // @public @@ -132,9 +132,9 @@ export type CreateApi = { BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', - TagTypes extends string = never + TagTypes extends string = never, >( - options: CreateApiOptions + options: CreateApiOptions, ): Api } @@ -148,11 +148,11 @@ export interface CreateApiOptions< BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', - TagTypes extends string = never + TagTypes extends string = never, > { baseQuery: BaseQuery endpoints( - build: EndpointBuilder + build: EndpointBuilder, ): Definitions keepUnusedDataFor?: number reducerPath?: ReducerPath @@ -169,7 +169,7 @@ export type EndpointDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = | QueryDefinition | MutationDefinition @@ -231,17 +231,17 @@ export type Module = { BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, >( api: Api, options: Required< CreateApiOptions >, - context: ApiContext + context: ApiContext, ): { injectEndpoint( endpointName: string, - definition: EndpointDefinition + definition: EndpointDefinition, ): void } } @@ -252,7 +252,7 @@ export type MutationDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = BaseEndpointDefinition & MutationExtraOptions @@ -262,7 +262,7 @@ export type QueryDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = BaseEndpointDefinition & QueryExtraOptions @@ -305,8 +305,8 @@ export function setupListeners( onFocusLost: typeof onFocusLost onOnline: typeof onOnline onOffline: typeof onOffline - } - ) => () => void + }, + ) => () => void, ): () => void // @public (undocumented) diff --git a/packages/toolkit/etc/rtk-query.api.md b/packages/toolkit/etc/rtk-query.api.md index dea69f7421..160ec14fe7 100644 --- a/packages/toolkit/etc/rtk-query.api.md +++ b/packages/toolkit/etc/rtk-query.api.md @@ -14,13 +14,13 @@ export type Api< Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string, - Enhancers extends ModuleName = CoreModule + Enhancers extends ModuleName = CoreModule, > = UnionToIntersection< ApiModules[Enhancers] > & { injectEndpoints(_: { endpoints: ( - build: EndpointBuilder + build: EndpointBuilder, ) => NewDefinitions overrideExisting?: boolean }): Api< @@ -56,17 +56,17 @@ export interface ApiModules< BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, > {} // @public (undocumented) export type BaseQueryEnhancer< AdditionalArgs = unknown, AdditionalDefinitionExtraOptions = unknown, - Config = void + Config = void, > = ( baseQuery: BaseQuery, - config: Config + config: Config, ) => BaseQueryFn< BaseQueryArg & AdditionalArgs, BaseQueryResult, @@ -82,11 +82,11 @@ export type BaseQueryFn< DefinitionExtraOptions = { copyWithStructuralSharing?: boolean }, - Meta = {} + Meta = {}, > = ( args: Args, api: BaseQueryApi, - extraOptions: DefinitionExtraOptions + extraOptions: DefinitionExtraOptions, ) => MaybePromise> // @public @@ -106,9 +106,9 @@ export type CreateApi = { BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', - TagTypes extends string = never + TagTypes extends string = never, >( - options: CreateApiOptions + options: CreateApiOptions, ): Api } @@ -120,11 +120,11 @@ export interface CreateApiOptions< BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', - TagTypes extends string = never + TagTypes extends string = never, > { baseQuery: BaseQuery endpoints( - build: EndpointBuilder + build: EndpointBuilder, ): Definitions extractRehydrationInfo?: ( action: UnknownAction, @@ -132,7 +132,7 @@ export interface CreateApiOptions< reducerPath, }: { reducerPath: ReducerPath - } + }, ) => | undefined | CombinedState< @@ -156,7 +156,7 @@ export type EndpointDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = | QueryDefinition | MutationDefinition @@ -240,7 +240,7 @@ export type Module = { BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, >( api: Api, options: WithRequiredProp< @@ -254,11 +254,11 @@ export type Module = { | 'tagTypes' | 'structuralSharing' >, - context: ApiContext + context: ApiContext, ): { injectEndpoint( endpointName: string, - definition: EndpointDefinition + definition: EndpointDefinition, ): void } } @@ -269,7 +269,7 @@ export type MutationDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = BaseEndpointDefinition & MutationExtraOptions @@ -279,7 +279,7 @@ export type QueryDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = BaseEndpointDefinition & QueryExtraOptions @@ -314,8 +314,8 @@ export function setupListeners( onFocusLost: typeof onFocusLost onOnline: typeof onOnline onOffline: typeof onOffline - } - ) => () => void + }, + ) => () => void, ): () => void // @public @deprecated (undocumented) diff --git a/packages/toolkit/scripts/mangleErrors.cjs b/packages/toolkit/scripts/mangleErrors.cjs index 96581df353..f777995f13 100644 --- a/packages/toolkit/scripts/mangleErrors.cjs +++ b/packages/toolkit/scripts/mangleErrors.cjs @@ -22,7 +22,7 @@ const evalToString = (ast) => { return ast.quasis.reduce( (concatenatedValue, templateElement) => concatenatedValue + templateElement.value.raw, - '' + '', ) case 'Identifier': return ast.name @@ -114,20 +114,20 @@ module.exports = (babel) => { path, 'formatProdErrorMessage', '@reduxjs/toolkit', - { nameHint: 'formatProdErrorMessage' } + { nameHint: 'formatProdErrorMessage' }, ) // Creates a function call to output the message to the error code page on the website const prodMessage = t.callExpression( formatProdErrorMessageIdentifier, - [t.numericLiteral(errorIndex)] + [t.numericLiteral(errorIndex)], ) if (minify) { path.replaceWith( t.throwStatement( - t.newExpression(t.identifier('Error'), [prodMessage]) - ) + t.newExpression(t.identifier('Error'), [prodMessage]), + ), ) } else { path.replaceWith( @@ -137,13 +137,13 @@ module.exports = (babel) => { t.binaryExpression( '===', t.identifier('process.env.NODE_ENV'), - t.stringLiteral('production') + t.stringLiteral('production'), ), prodMessage, - path.node.argument.arguments[0] + path.node.argument.arguments[0], ), - ]) - ) + ]), + ), ) } } diff --git a/packages/toolkit/src/actionCreatorInvariantMiddleware.ts b/packages/toolkit/src/actionCreatorInvariantMiddleware.ts index 1f3a47e0d4..4b95495cbe 100644 --- a/packages/toolkit/src/actionCreatorInvariantMiddleware.ts +++ b/packages/toolkit/src/actionCreatorInvariantMiddleware.ts @@ -19,7 +19,7 @@ Make sure you're calling the action creator before dispatching, i.e. \`dispatch( } export function createActionCreatorInvariantMiddleware( - options: ActionCreatorInvariantMiddlewareOptions = {} + options: ActionCreatorInvariantMiddlewareOptions = {}, ): Middleware { if (process.env.NODE_ENV === 'production') { return () => (next) => (action) => next(action) diff --git a/packages/toolkit/src/autoBatchEnhancer.ts b/packages/toolkit/src/autoBatchEnhancer.ts index eb4dd8ca56..560cb49e18 100644 --- a/packages/toolkit/src/autoBatchEnhancer.ts +++ b/packages/toolkit/src/autoBatchEnhancer.ts @@ -66,10 +66,10 @@ export const autoBatchEnhancer = options.type === 'tick' ? queueMicrotask : options.type === 'raf' - ? rAF - : options.type === 'callback' - ? options.queueNotification - : createQueueWithTimer(options.timeout) + ? rAF + : options.type === 'callback' + ? options.queueNotification + : createQueueWithTimer(options.timeout) const notifyListeners = () => { // We're running at the end of the event loop tick. diff --git a/packages/toolkit/src/combineSlices.ts b/packages/toolkit/src/combineSlices.ts index 1a10538cd8..f045f14f17 100644 --- a/packages/toolkit/src/combineSlices.ts +++ b/packages/toolkit/src/combineSlices.ts @@ -17,19 +17,11 @@ type SliceLike = { type AnySliceLike = SliceLike -type SliceLikeReducerPath = A extends SliceLike< - infer ReducerPath, - any -> - ? ReducerPath - : never - -type SliceLikeState = A extends SliceLike< - any, - infer State -> - ? State - : never +type SliceLikeReducerPath = + A extends SliceLike ? ReducerPath : never + +type SliceLikeState = + A extends SliceLike ? State : never export type WithSlice = { [Path in SliceLikeReducerPath]: SliceLikeState @@ -56,7 +48,7 @@ export type InjectConfig = { */ export interface CombinedSliceReducer< InitialState, - DeclaredState = InitialState + DeclaredState = InitialState, > extends Reducer> { /** * Provide a type for slices that will be injected lazily. @@ -106,7 +98,7 @@ export interface CombinedSliceReducer< */ inject>>( slice: Sl, - config?: InjectConfig + config?: InjectConfig, ): CombinedSliceReducer>> /** @@ -126,7 +118,7 @@ export interface CombinedSliceReducer< ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State) >, - config?: InjectConfig + config?: InjectConfig, ): CombinedSliceReducer< InitialState, Id>> @@ -212,7 +204,7 @@ export interface CombinedSliceReducer< * ``` */ unknown>( - selectorFn: Selector + selectorFn: Selector, ): ( state: WithOptionalProp< Parameters[0], @@ -276,7 +268,7 @@ export interface CombinedSliceReducer< */ < Selector extends (state: DeclaredState, ...args: any[]) => unknown, - RootState + RootState, >( selectorFn: Selector, selectState: ( @@ -285,7 +277,7 @@ export interface CombinedSliceReducer< ) => WithOptionalProp< Parameters[0], Exclude - > + >, ): ( state: RootState, ...args: Tail> @@ -310,7 +302,7 @@ type InitialState> = > const isSliceLike = ( - maybeSliceLike: AnySliceLike | ReducerMap + maybeSliceLike: AnySliceLike | ReducerMap, ): maybeSliceLike is AnySliceLike => 'reducerPath' in maybeSliceLike && typeof maybeSliceLike.reducerPath === 'string' @@ -319,7 +311,7 @@ const getReducers = (slices: Array) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer] as const] - : Object.entries(sliceOrMap) + : Object.entries(sliceOrMap), ) const ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original') @@ -330,7 +322,7 @@ const stateProxyMap = new WeakMap() const createStateProxy = ( state: State, - reducerMap: Partial> + reducerMap: Partial>, ) => emplace(stateProxyMap, state, { insert: () => @@ -349,7 +341,7 @@ const createStateProxy = ( `If the state passed to the reducer is undefined, you must ` + `explicitly return the initial state. The initial state may ` + `not be undefined. If you don't want to set a value for this reducer, ` + - `you can use null instead of undefined.` + `you can use null instead of undefined.`, ) } return reducerResult @@ -370,8 +362,8 @@ const original = (state: any) => { export function combineSlices< Slices extends [ AnySliceLike | ReducerMap, - ...Array - ] + ...Array, + ], >(...slices: Slices): CombinedSliceReducer>> { const reducerMap = Object.fromEntries(getReducers(slices)) @@ -381,7 +373,7 @@ export function combineSlices< function combinedReducer( state: Record, - action: UnknownAction + action: UnknownAction, ) { return reducer(state, action) } @@ -390,7 +382,7 @@ export function combineSlices< const inject = ( slice: AnySliceLike, - config: InjectConfig = {} + config: InjectConfig = {}, ): typeof combinedReducer => { const { reducerPath, reducer: reducerToInject } = slice @@ -405,7 +397,7 @@ export function combineSlices< process.env.NODE_ENV === 'development' ) { console.error( - `called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\`` + `called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``, ) } @@ -422,19 +414,19 @@ export function combineSlices< const selector = Object.assign( function makeSelector( selectorFn: (state: State, ...args: Args) => any, - selectState?: (rootState: RootState, ...args: Args) => State + selectState?: (rootState: RootState, ...args: Args) => State, ) { return function selector(state: State, ...args: Args) { return selectorFn( createStateProxy( selectState ? selectState(state as any, ...args) : state, - reducerMap + reducerMap, ), - ...args + ...args, ) } }, - { original } + { original }, ) return Object.assign(combinedReducer, { inject, selector }) as any diff --git a/packages/toolkit/src/configureStore.ts b/packages/toolkit/src/configureStore.ts index e1b1a491e1..05b3bb8914 100644 --- a/packages/toolkit/src/configureStore.ts +++ b/packages/toolkit/src/configureStore.ts @@ -44,7 +44,7 @@ export interface ConfigureStoreOptions< A extends Action = UnknownAction, M extends Tuple> = Tuple>, E extends Tuple = Tuple, - P = S + P = S, > { /** * A single reducer function that will be used as the root reducer, or an @@ -103,7 +103,7 @@ type Enhancers = ReadonlyArray export type EnhancedStore< S = any, A extends Action = UnknownAction, - E extends Enhancers = Enhancers + E extends Enhancers = Enhancers, > = ExtractStoreExtensions & Store>> @@ -122,7 +122,7 @@ export function configureStore< E extends Tuple = Tuple< [StoreEnhancer<{ dispatch: ExtractDispatchExtensions }>, StoreEnhancer] >, - P = S + P = S, >(options: ConfigureStoreOptions): EnhancedStore { const getDefaultMiddleware = buildGetDefaultMiddleware() @@ -142,7 +142,7 @@ export function configureStore< rootReducer = combineReducers(reducer) as unknown as Reducer } else { throw new Error( - '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers' + '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers', ) } @@ -156,7 +156,7 @@ export function configureStore< if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) { throw new Error( - 'when using a middleware builder function, an array of middleware must be returned' + 'when using a middleware builder function, an array of middleware must be returned', ) } } else { @@ -167,7 +167,7 @@ export function configureStore< finalMiddleware.some((item: any) => typeof item !== 'function') ) { throw new Error( - 'each middleware provided to configureStore must be a function' + 'each middleware provided to configureStore must be a function', ) } @@ -202,7 +202,7 @@ export function configureStore< storeEnhancers.some((item: any) => typeof item !== 'function') ) { throw new Error( - 'each enhancer provided to configureStore must be a function' + 'each enhancer provided to configureStore must be a function', ) } if ( @@ -211,7 +211,7 @@ export function configureStore< !storeEnhancers.includes(middlewareEnhancer) ) { console.error( - 'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`' + 'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`', ) } diff --git a/packages/toolkit/src/createAction.ts b/packages/toolkit/src/createAction.ts index 7e347c0472..ea8958288d 100644 --- a/packages/toolkit/src/createAction.ts +++ b/packages/toolkit/src/createAction.ts @@ -22,7 +22,7 @@ export type PayloadAction< P = void, T extends string = string, M = never, - E = never + E = never, > = { payload: P type: T @@ -57,24 +57,25 @@ export type PrepareAction

= */ export type _ActionCreatorWithPreparedPayload< PA extends PrepareAction | void, - T extends string = string -> = PA extends PrepareAction - ? ActionCreatorWithPreparedPayload< - Parameters, - P, - T, - ReturnType extends { - error: infer E - } - ? E - : never, - ReturnType extends { - meta: infer M - } - ? M - : never - > - : void + T extends string = string, +> = + PA extends PrepareAction + ? ActionCreatorWithPreparedPayload< + Parameters, + P, + T, + ReturnType extends { + error: infer E + } + ? E + : never, + ReturnType extends { + meta: infer M + } + ? M + : never + > + : void /** * Basic type for all action creators. @@ -104,7 +105,7 @@ export interface ActionCreatorWithPreparedPayload< P, T extends string = string, E = never, - M = never + M = never, > extends BaseActionCreator { /** * Calling this {@link redux#ActionCreator} with `Args` will return @@ -171,7 +172,7 @@ export interface ActionCreatorWithPayload * @public */ export interface ActionCreatorWithNonInferrablePayload< - T extends string = string + T extends string = string, > extends BaseActionCreator { /** * Calling this {@link redux#ActionCreator} with an argument will @@ -193,7 +194,7 @@ export interface ActionCreatorWithNonInferrablePayload< export type PayloadActionCreator< P = void, T extends string = string, - PA extends PrepareAction

| void = void + PA extends PrepareAction

| void = void, > = IfPrepareActionMethodProvided< PA, _ActionCreatorWithPreparedPayload, @@ -233,7 +234,7 @@ export type PayloadActionCreator< * @public */ export function createAction

( - type: T + type: T, ): PayloadActionCreator /** @@ -250,10 +251,10 @@ export function createAction

( */ export function createAction< PA extends PrepareAction, - T extends string = string + T extends string = string, >( type: T, - prepareAction: PA + prepareAction: PA, ): PayloadActionCreator['payload'], T, PA> export function createAction(type: string, prepareAction?: Function): any { @@ -288,7 +289,7 @@ export function createAction(type: string, prepareAction?: Function): any { * Returns true if value is an RTK-like action creator, with a static type property and match method. */ export function isActionCreator( - action: unknown + action: unknown, ): action is BaseActionCreator & Function { return ( typeof action === 'function' && @@ -319,5 +320,5 @@ function isValidKey(key: string) { type IfPrepareActionMethodProvided< PA extends PrepareAction | void, True, - False + False, > = PA extends (...args: any[]) => any ? True : False diff --git a/packages/toolkit/src/createAsyncThunk.ts b/packages/toolkit/src/createAsyncThunk.ts index c6b1517b3b..f384ab9af2 100644 --- a/packages/toolkit/src/createAsyncThunk.ts +++ b/packages/toolkit/src/createAsyncThunk.ts @@ -26,7 +26,7 @@ export type BaseThunkAPI< D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, - FulfilledMeta = unknown + FulfilledMeta = unknown, > = { dispatch: D getState: () => S @@ -39,7 +39,7 @@ export type BaseThunkAPI< (value: RejectedValue) => RejectWithValue, ( value: RejectedValue, - meta: RejectedMeta + meta: RejectedMeta, ) => RejectWithValue > fulfillWithValue: IsUnknown< @@ -47,7 +47,7 @@ export type BaseThunkAPI< (value: FulfilledValue) => FulfilledValue, ( value: FulfilledValue, - meta: FulfilledMeta + meta: FulfilledMeta, ) => FulfillWithMeta > } @@ -77,7 +77,7 @@ class RejectWithValue { private readonly _type!: 'RejectWithValue' constructor( public readonly payload: Payload, - public readonly meta: RejectedMeta + public readonly meta: RejectedMeta, ) {} } @@ -89,7 +89,7 @@ class FulfillWithMeta { private readonly _type!: 'FulfillWithMeta' constructor( public readonly payload: Payload, - public readonly meta: FulfilledMeta + public readonly meta: FulfilledMeta, ) {} } @@ -199,7 +199,7 @@ type MaybePromise = T | Promise | (T extends any ? Promise : never) */ export type AsyncThunkPayloadCreatorReturnValue< Returned, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, > = MaybePromise< | IsUnknown< GetFulfilledMeta, @@ -220,10 +220,10 @@ export type AsyncThunkPayloadCreatorReturnValue< export type AsyncThunkPayloadCreator< Returned, ThunkArg = void, - ThunkApiConfig extends AsyncThunkConfig = {} + ThunkApiConfig extends AsyncThunkConfig = {}, > = ( arg: ThunkArg, - thunkAPI: GetThunkAPI + thunkAPI: GetThunkAPI, ) => AsyncThunkPayloadCreatorReturnValue /** @@ -238,11 +238,11 @@ export type AsyncThunkPayloadCreator< export type AsyncThunkAction< Returned, ThunkArg, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, > = ( dispatch: GetDispatch, getState: () => GetState, - extra: GetExtra + extra: GetExtra, ) => SafePromise< | ReturnType> | ReturnType> @@ -256,7 +256,7 @@ export type AsyncThunkAction< type AsyncThunkActionCreator< Returned, ThunkArg, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, > = IsAny< ThunkArg, // any handling @@ -265,19 +265,25 @@ type AsyncThunkActionCreator< unknown extends ThunkArg ? (arg: ThunkArg) => AsyncThunkAction // argument not specified or specified as void or undefined : [ThunkArg] extends [void] | [undefined] - ? () => AsyncThunkAction // argument contains void - : [void] extends [ThunkArg] // make optional - ? (arg?: ThunkArg) => AsyncThunkAction // argument contains undefined - : [undefined] extends [ThunkArg] - ? WithStrictNullChecks< - // with strict nullChecks: make optional - ( - arg?: ThunkArg - ) => AsyncThunkAction, - // without strict null checks this will match everything, so don't make it optional - (arg: ThunkArg) => AsyncThunkAction - > // default case: normal argument - : (arg: ThunkArg) => AsyncThunkAction + ? () => AsyncThunkAction // argument contains void + : [void] extends [ThunkArg] // make optional + ? ( + arg?: ThunkArg, + ) => AsyncThunkAction // argument contains undefined + : [undefined] extends [ThunkArg] + ? WithStrictNullChecks< + // with strict nullChecks: make optional + ( + arg?: ThunkArg, + ) => AsyncThunkAction, + // without strict null checks this will match everything, so don't make it optional + ( + arg: ThunkArg, + ) => AsyncThunkAction + > // default case: normal argument + : ( + arg: ThunkArg, + ) => AsyncThunkAction > /** @@ -287,7 +293,7 @@ type AsyncThunkActionCreator< */ export type AsyncThunkOptions< ThunkArg = void, - ThunkApiConfig extends AsyncThunkConfig = {} + ThunkApiConfig extends AsyncThunkConfig = {}, > = { /** * A method to control whether the asyncThunk should be executed. Has access to the @@ -297,7 +303,7 @@ export type AsyncThunkOptions< */ condition?( arg: ThunkArg, - api: Pick, 'getState' | 'extra'> + api: Pick, 'getState' | 'extra'>, ): MaybePromise /** * If `condition` returns `false`, the asyncThunk will be skipped. @@ -330,7 +336,7 @@ export type AsyncThunkOptions< arg: ThunkArg requestId: string }, - api: Pick, 'getState' | 'extra'> + api: Pick, 'getState' | 'extra'>, ): GetPendingMeta }, { @@ -342,14 +348,14 @@ export type AsyncThunkOptions< arg: ThunkArg requestId: string }, - api: Pick, 'getState' | 'extra'> + api: Pick, 'getState' | 'extra'>, ): GetPendingMeta } > export type AsyncThunkPendingActionCreator< ThunkArg, - ThunkApiConfig = {} + ThunkApiConfig = {}, > = ActionCreatorWithPreparedPayload< [string, ThunkArg, GetPendingMeta?], undefined, @@ -364,14 +370,14 @@ export type AsyncThunkPendingActionCreator< export type AsyncThunkRejectedActionCreator< ThunkArg, - ThunkApiConfig = {} + ThunkApiConfig = {}, > = ActionCreatorWithPreparedPayload< [ Error | null, string, ThunkArg, GetRejectValue?, - GetRejectedMeta? + GetRejectedMeta?, ], GetRejectValue | undefined, string, @@ -393,7 +399,7 @@ export type AsyncThunkRejectedActionCreator< export type AsyncThunkFulfilledActionCreator< Returned, ThunkArg, - ThunkApiConfig = {} + ThunkApiConfig = {}, > = ActionCreatorWithPreparedPayload< [Returned, string, ThunkArg, GetFulfilledMeta?], Returned, @@ -415,7 +421,7 @@ export type AsyncThunkFulfilledActionCreator< export type AsyncThunk< Returned, ThunkArg, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, > = AsyncThunkActionCreator & { pending: AsyncThunkPendingActionCreator rejected: AsyncThunkRejectedActionCreator @@ -426,7 +432,7 @@ export type AsyncThunk< > // matchSettled? settled: ( - action: any + action: any, ) => action is ReturnType< | AsyncThunkRejectedActionCreator | AsyncThunkFulfilledActionCreator @@ -455,7 +461,7 @@ type CreateAsyncThunk = { ThunkArg, CurriedThunkApiConfig >, - options?: AsyncThunkOptions + options?: AsyncThunkOptions, ): AsyncThunk /** @@ -476,7 +482,7 @@ type CreateAsyncThunk = { options?: AsyncThunkOptions< ThunkArg, OverrideThunkApiConfigs - > + >, ): AsyncThunk< Returned, ThunkArg, @@ -492,7 +498,7 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { function createAsyncThunk< Returned, ThunkArg, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, >( typePrefix: string, payloadCreator: AsyncThunkPayloadCreator< @@ -500,7 +506,7 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { ThunkArg, ThunkApiConfig >, - options?: AsyncThunkOptions + options?: AsyncThunkOptions, ): AsyncThunk { type RejectedValue = GetRejectValue type PendingMeta = GetPendingMeta @@ -517,7 +523,7 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { payload: Returned, requestId: string, arg: ThunkArg, - meta?: FulfilledMeta + meta?: FulfilledMeta, ) => ({ payload, meta: { @@ -526,7 +532,7 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { requestId, requestStatus: 'fulfilled' as const, }, - }) + }), ) const pending: AsyncThunkPendingActionCreator = @@ -540,7 +546,7 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { requestId, requestStatus: 'pending' as const, }, - }) + }), ) const rejected: AsyncThunkRejectedActionCreator = @@ -551,11 +557,11 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { requestId: string, arg: ThunkArg, payload?: RejectedValue, - meta?: RejectedMeta + meta?: RejectedMeta, ) => ({ payload, error: ((options && options.serializeError) || miniSerializeError)( - error || 'Rejected' + error || 'Rejected', ) as GetSerializedErrorType, meta: { ...((meta as any) || {}), @@ -566,11 +572,11 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { aborted: error?.name === 'AbortError', condition: error?.name === 'ConditionError', }, - }) + }), ) function actionCreator( - arg: ThunkArg + arg: ThunkArg, ): AsyncThunkAction { return (dispatch, getState, extra) => { const requestId = options?.idGenerator @@ -617,9 +623,9 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { arg, options?.getPendingMeta?.( { requestId, arg }, - { getState, extra } - ) - ) as any + { getState, extra }, + ), + ) as any, ) finalAction = await Promise.race([ abortedPromise, @@ -633,14 +639,14 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { abort, rejectWithValue: (( value: RejectedValue, - meta?: RejectedMeta + meta?: RejectedMeta, ) => { return new RejectWithValue(value, meta) }) as any, fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => { return new FulfillWithMeta(value, meta) }) as any, - }) + }), ).then((result) => { if (result instanceof RejectWithValue) { throw result @@ -700,7 +706,7 @@ export const createAsyncThunk = /* @__PURE__ */ (() => { fulfilled, settled: isAnyOf(rejected, fulfilled), typePrefix, - } + }, ) } createAsyncThunk.withTypes = () => createAsyncThunk @@ -723,7 +729,7 @@ type UnwrappedActionPayload = Exclude< * @public */ export function unwrapResult( - action: R + action: R, ): UnwrappedActionPayload { if (action.meta && action.meta.rejectedWithValue) { throw action.payload diff --git a/packages/toolkit/src/createDraftSafeSelector.ts b/packages/toolkit/src/createDraftSafeSelector.ts index 67b5465687..825fc0db32 100644 --- a/packages/toolkit/src/createDraftSafeSelector.ts +++ b/packages/toolkit/src/createDraftSafeSelector.ts @@ -13,7 +13,7 @@ export const createDraftSafeSelectorCreator: typeof createSelectorCreator = ( Object.assign(wrappedSelector, selector) return wrappedSelector as any }, - { withTypes: () => createDraftSafeSelector } + { withTypes: () => createDraftSafeSelector }, ) return createDraftSafeSelector } diff --git a/packages/toolkit/src/createReducer.ts b/packages/toolkit/src/createReducer.ts index f0f2ac50be..564a1f13b0 100644 --- a/packages/toolkit/src/createReducer.ts +++ b/packages/toolkit/src/createReducer.ts @@ -47,7 +47,7 @@ export type ActionMatcherDescriptionCollection = Array< */ export type CaseReducer = ( state: Draft, - action: A + action: A, ) => NoInfer | void | Draft> /** @@ -139,12 +139,12 @@ const reducer = createReducer( */ export function createReducer>( initialState: S | (() => S), - mapOrBuilderCallback: (builder: ActionReducerMapBuilder) => void + mapOrBuilderCallback: (builder: ActionReducerMapBuilder) => void, ): ReducerWithInitialState { if (process.env.NODE_ENV !== 'production') { if (typeof mapOrBuilderCallback === 'object') { throw new Error( - "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer" + "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer", ) } } @@ -196,7 +196,7 @@ export function createReducer>( return previousState } throw Error( - 'A case reducer on a non-draftable value must not return undefined' + 'A case reducer on a non-draftable value must not return undefined', ) } diff --git a/packages/toolkit/src/createSlice.ts b/packages/toolkit/src/createSlice.ts index 3bbe4e98c5..441fbbcc6a 100644 --- a/packages/toolkit/src/createSlice.ts +++ b/packages/toolkit/src/createSlice.ts @@ -50,7 +50,7 @@ export interface Slice< CaseReducers extends SliceCaseReducers = SliceCaseReducers, Name extends string = string, ReducerPath extends string = Name, - Selectors extends SliceSelectors = SliceSelectors + Selectors extends SliceSelectors = SliceSelectors, > { /** * The slice name. @@ -94,7 +94,7 @@ export interface Slice< * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state) */ getSelectors( - selectState: (rootState: RootState) => State + selectState: (rootState: RootState) => State, ): Id> /** @@ -114,10 +114,10 @@ export interface Slice< injectable: { inject: ( slice: { reducerPath: string; reducer: Reducer }, - config?: InjectConfig + config?: InjectConfig, ) => void }, - config?: InjectIntoConfig + config?: InjectIntoConfig, ): InjectedSlice /** @@ -138,7 +138,7 @@ interface InjectedSlice< CaseReducers extends SliceCaseReducers = SliceCaseReducers, Name extends string = string, ReducerPath extends string = Name, - Selectors extends SliceSelectors = SliceSelectors + Selectors extends SliceSelectors = SliceSelectors, > extends Omit< Slice, 'getSelectors' | 'selectors' @@ -152,7 +152,7 @@ interface InjectedSlice< * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state) */ getSelectors( - selectState: (rootState: RootState) => State | undefined + selectState: (rootState: RootState) => State | undefined, ): Id> /** @@ -186,7 +186,7 @@ export interface CreateSliceOptions< CR extends SliceCaseReducers = SliceCaseReducers, Name extends string = string, ReducerPath extends string = Name, - Selectors extends SliceSelectors = SliceSelectors + Selectors extends SliceSelectors = SliceSelectors, > { /** * The slice's name. Used to namespace the generated action types. @@ -274,7 +274,7 @@ interface ReducerDefinition { export interface CaseReducerDefinition< S = any, - A extends Action = UnknownAction + A extends Action = UnknownAction, > extends CaseReducer, ReducerDefinition {} @@ -290,7 +290,7 @@ export type CaseReducerWithPrepare = { export interface CaseReducerWithPrepareDefinition< State, - Action extends PayloadAction + Action extends PayloadAction, > extends CaseReducerWithPrepare, ReducerDefinition {} @@ -298,7 +298,7 @@ export interface AsyncThunkSliceReducerConfig< State, ThunkArg extends any, Returned = unknown, - ThunkApiConfig extends AsyncThunkConfig = {} + ThunkApiConfig extends AsyncThunkConfig = {}, > { pending?: CaseReducer< State, @@ -325,7 +325,7 @@ export interface AsyncThunkSliceReducerDefinition< State, ThunkArg extends any, Returned = unknown, - ThunkApiConfig extends AsyncThunkConfig = {} + ThunkApiConfig extends AsyncThunkConfig = {}, > extends AsyncThunkSliceReducerConfig< State, ThunkArg, @@ -347,7 +347,8 @@ type PreventCircular = { interface AsyncThunkCreator< State, - CurriedThunkApiConfig extends PreventCircular = PreventCircular + CurriedThunkApiConfig extends + PreventCircular = PreventCircular, > { ( payloadCreator: AsyncThunkPayloadCreator< @@ -360,7 +361,7 @@ interface AsyncThunkCreator< ThunkArg, Returned, CurriedThunkApiConfig - > + >, ): AsyncThunkSliceReducerDefinition< State, ThunkArg, @@ -370,7 +371,7 @@ interface AsyncThunkCreator< < Returned, ThunkArg, - ThunkApiConfig extends PreventCircular = {} + ThunkApiConfig extends PreventCircular = {}, >( payloadCreator: AsyncThunkPayloadCreator< Returned, @@ -382,10 +383,10 @@ interface AsyncThunkCreator< ThunkArg, Returned, ThunkApiConfig - > + >, ): AsyncThunkSliceReducerDefinition withTypes< - ThunkApiConfig extends PreventCircular + ThunkApiConfig extends PreventCircular, >(): AsyncThunkCreator< State, OverrideThunkApiConfigs @@ -394,10 +395,10 @@ interface AsyncThunkCreator< export interface ReducerCreators { reducer( - caseReducer: CaseReducer + caseReducer: CaseReducer, ): CaseReducerDefinition reducer( - caseReducer: CaseReducer> + caseReducer: CaseReducer>, ): CaseReducerDefinition> asyncThunk: AsyncThunkCreator @@ -407,7 +408,7 @@ export interface ReducerCreators { reducer: CaseReducer< State, ReturnType<_ActionCreatorWithPreparedPayload> - > + >, ): { _reducerDefinitionType: ReducerType.reducerWithPrepare prepare: Prepare @@ -448,7 +449,7 @@ export type SliceSelectors = { type SliceActionType< SliceName extends string, - ActionName extends keyof any + ActionName extends keyof any, > = ActionName extends string | number ? `${SliceName}/${ActionName}` : string /** @@ -458,7 +459,7 @@ type SliceActionType< */ export type CaseReducerActions< CaseReducers extends SliceCaseReducers, - SliceName extends string + SliceName extends string, > = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends { prepare: any } @@ -467,21 +468,21 @@ export type CaseReducerActions< SliceActionType > : Definition extends AsyncThunkSliceReducerDefinition< - any, - infer ThunkArg, - infer Returned, - infer ThunkApiConfig - > - ? AsyncThunk - : Definition extends { reducer: any } - ? ActionCreatorForCaseReducer< - Definition['reducer'], - SliceActionType - > - : ActionCreatorForCaseReducer< - Definition, - SliceActionType - > + any, + infer ThunkArg, + infer Returned, + infer ThunkApiConfig + > + ? AsyncThunk + : Definition extends { reducer: any } + ? ActionCreatorForCaseReducer< + Definition['reducer'], + SliceActionType + > + : ActionCreatorForCaseReducer< + Definition, + SliceActionType + > : never } @@ -492,7 +493,7 @@ export type CaseReducerActions< */ type ActionCreatorForCaseReducerWithPrepare< CR extends { prepare: any }, - Type extends string + Type extends string, > = _ActionCreatorWithPreparedPayload /** @@ -502,7 +503,7 @@ type ActionCreatorForCaseReducerWithPrepare< */ type ActionCreatorForCaseReducer = CR extends ( state: any, - action: infer Action + action: infer Action, ) => any ? Action extends { payload: infer P } ? PayloadActionCreator @@ -525,20 +526,17 @@ type SliceDefinedCaseReducers> = { > > : Definition extends { - reducer: infer Reducer - } - ? Reducer - : Definition + reducer: infer Reducer + } + ? Reducer + : Definition : never } -type RemappedSelector = S extends Selector< - any, - infer R, - infer P -> - ? Selector & { unwrapped: S } - : never +type RemappedSelector = + S extends Selector + ? Selector & { unwrapped: S } + : never /** * Extracts the final selector type from the `selectors` object. @@ -548,7 +546,7 @@ type RemappedSelector = S extends Selector< type SliceDefinedSelectors< State, Selectors extends SliceSelectors, - RootState + RootState, > = { [K in keyof Selectors as string extends K ? never : K]: RemappedSelector< Selectors[K], @@ -570,17 +568,16 @@ type SliceDefinedSelectors< */ export type ValidateSliceCaseReducers< S, - ACR extends SliceCaseReducers -> = ACR & - { - [T in keyof ACR]: ACR[T] extends { - reducer(s: S, action?: infer A): any - } - ? { - prepare(...a: never[]): Omit - } - : {} + ACR extends SliceCaseReducers, +> = ACR & { + [T in keyof ACR]: ACR[T] extends { + reducer(s: S, action?: infer A): any } + ? { + prepare(...a: never[]): Omit + } + : {} +} function getType(slice: string, actionKey: string): string { return `${slice}/${actionKey}` @@ -599,7 +596,7 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { CaseReducers extends SliceCaseReducers, Name extends string, Selectors extends SliceSelectors, - ReducerPath extends string = Name + ReducerPath extends string = Name, >( options: CreateSliceOptions< State, @@ -607,7 +604,7 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { Name, ReducerPath, Selectors - > + >, ): Slice { const { name, reducerPath = name as unknown as ReducerPath } = options if (!name) { @@ -620,7 +617,7 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { ) { if (options.initialState === undefined) { console.error( - 'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`' + 'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`', ) } } @@ -642,7 +639,7 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { const contextMethods: ReducerHandlingContextMethods = { addCase( typeOrActionCreator: string | TypedActionCreator, - reducer: CaseReducer + reducer: CaseReducer, ) { const type = typeof typeOrActionCreator === 'string' @@ -650,13 +647,13 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { : typeOrActionCreator.type if (!type) { throw new Error( - '`context.addCase` cannot be called with an empty action type' + '`context.addCase` cannot be called with an empty action type', ) } if (type in context.sliceCaseReducersByType) { throw new Error( '`context.addCase` cannot be called with two reducers for the same action type: ' + - type + type, ) } context.sliceCaseReducersByType[type] = reducer @@ -688,13 +685,13 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { reducerDetails, reducerDefinition, contextMethods, - cAT + cAT, ) } else { handleNormalReducerDefinition( reducerDetails, reducerDefinition, - contextMethods + contextMethods, ) } }) @@ -703,7 +700,7 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { if (process.env.NODE_ENV !== 'production') { if (typeof options.extraReducers === 'object') { throw new Error( - "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice" + "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice", ) } } @@ -763,7 +760,7 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { function makeSelectorProps( reducerPath: CurrentReducerPath, - injected = false + injected = false, ): Pick< Slice, 'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath' @@ -775,14 +772,14 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { sliceState = getInitialState() } else if (process.env.NODE_ENV !== 'production') { throw new Error( - 'selectSlice returned undefined for an uninjected slice reducer' + 'selectSlice returned undefined for an uninjected slice reducer', ) } } return sliceState } function getSelectors( - selectState: (rootState: any) => State = selectSelf + selectState: (rootState: any) => State = selectSelf, ) { const selectorCache = emplace(injectedSelectorCache, injected, { insert: () => new WeakMap(), @@ -792,13 +789,13 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { insert: () => { const map: Record> = {} for (const [name, selector] of Object.entries( - options.selectors ?? {} + options.selectors ?? {}, )) { map[name] = wrapSelector( selector, selectState, getInitialState, - injected + injected, ) } return map @@ -839,7 +836,7 @@ function wrapSelector>( selector: S, selectState: Selector, getInitialState: () => State, - injected?: boolean + injected?: boolean, ) { function wrapper(rootState: NewState, ...args: any[]) { let sliceState = selectState(rootState) @@ -848,7 +845,7 @@ function wrapSelector>( sliceState = getInitialState() } else if (process.env.NODE_ENV !== 'production') { throw new Error( - 'selectState returned undefined for an uninjected slice reducer' + 'selectState returned undefined for an uninjected slice reducer', ) } } @@ -890,7 +887,7 @@ interface ReducerHandlingContextMethods { */ addCase>( actionCreator: ActionCreator, - reducer: CaseReducer> + reducer: CaseReducer>, ): ReducerHandlingContextMethods /** * Adds a case reducer to handle a single action type. @@ -899,7 +896,7 @@ interface ReducerHandlingContextMethods { */ addCase>( type: Type, - reducer: CaseReducer + reducer: CaseReducer, ): ReducerHandlingContextMethods /** @@ -915,7 +912,7 @@ interface ReducerHandlingContextMethods { */ addMatcher( matcher: TypeGuard, - reducer: CaseReducer + reducer: CaseReducer, ): ReducerHandlingContextMethods /** * Add an action to be exposed under the final `slice.actions` key. @@ -930,7 +927,7 @@ interface ReducerHandlingContextMethods { */ exposeAction( name: string, - actionCreator: Function + actionCreator: Function, ): ReducerHandlingContextMethods /** * Add a case reducer to be exposed under the final `slice.caseReducers` key. @@ -950,7 +947,7 @@ interface ReducerHandlingContextMethods { | Pick< AsyncThunkSliceReducerDefinition, 'fulfilled' | 'rejected' | 'pending' | 'settled' - > + >, ): ReducerHandlingContextMethods } @@ -966,7 +963,7 @@ interface ReducerDetails { function buildReducerCreators(): ReducerCreators { function asyncThunk( payloadCreator: AsyncThunkPayloadCreator, - config: AsyncThunkSliceReducerConfig + config: AsyncThunkSliceReducerConfig, ): AsyncThunkSliceReducerDefinition { return { _reducerDefinitionType: ReducerType.asyncThunk, @@ -987,7 +984,7 @@ function buildReducerCreators(): ReducerCreators { }[caseReducer.name], { _reducerDefinitionType: ReducerType.reducer, - } as const + } as const, ) }, preparedReducer(prepare, reducer) { @@ -1006,7 +1003,7 @@ function handleNormalReducerDefinition( maybeReducerWithPrepare: | CaseReducer | CaseReducerWithPrepare>, - context: ReducerHandlingContextMethods + context: ReducerHandlingContextMethods, ) { let caseReducer: CaseReducer let prepareCallback: PrepareAction | undefined @@ -1016,7 +1013,7 @@ function handleNormalReducerDefinition( !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare) ) { throw new Error( - 'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.' + 'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.', ) } caseReducer = maybeReducerWithPrepare.reducer @@ -1029,18 +1026,20 @@ function handleNormalReducerDefinition( .exposeCaseReducer(reducerName, caseReducer) .exposeAction( reducerName, - prepareCallback ? createAction(type, prepareCallback) : createAction(type) + prepareCallback + ? createAction(type, prepareCallback) + : createAction(type), ) } function isAsyncThunkSliceReducerDefinition( - reducerDefinition: any + reducerDefinition: any, ): reducerDefinition is AsyncThunkSliceReducerDefinition { return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk } function isCaseReducerWithPrepareDefinition( - reducerDefinition: any + reducerDefinition: any, ): reducerDefinition is CaseReducerWithPrepareDefinition { return ( reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare @@ -1051,12 +1050,12 @@ function handleThunkCaseReducerDefinition( { type, reducerName }: ReducerDetails, reducerDefinition: AsyncThunkSliceReducerDefinition, context: ReducerHandlingContextMethods, - cAT: typeof _createAsyncThunk | undefined + cAT: typeof _createAsyncThunk | undefined, ) { if (!cAT) { throw new Error( 'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' + - 'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.' + 'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.', ) } const { payloadCreator, fulfilled, pending, rejected, settled, options } = diff --git a/packages/toolkit/src/dynamicMiddleware/index.ts b/packages/toolkit/src/dynamicMiddleware/index.ts index 556998d142..2ad15b6c3e 100644 --- a/packages/toolkit/src/dynamicMiddleware/index.ts +++ b/packages/toolkit/src/dynamicMiddleware/index.ts @@ -18,9 +18,9 @@ import type { const createMiddlewareEntry = < State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, >( - middleware: Middleware + middleware: Middleware, ): MiddlewareEntry => ({ id: nanoid(), middleware, @@ -34,7 +34,7 @@ const matchInstance = export const createDynamicMiddleware = < State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, >(): DynamicMiddlewareInstance => { const instanceId = nanoid() const middlewareMap = new Map>() @@ -47,9 +47,9 @@ export const createDynamicMiddleware = < meta: { instanceId, }, - }) + }), ), - { withTypes: () => withMiddleware } + { withTypes: () => withMiddleware }, ) as WithMiddleware const addMiddleware = Object.assign( @@ -57,7 +57,7 @@ export const createDynamicMiddleware = < middlewares.forEach((middleware) => { let entry = find( Array.from(middlewareMap.values()), - (entry) => entry.middleware === middleware + (entry) => entry.middleware === middleware, ) if (!entry) { entry = createMiddlewareEntry(middleware) @@ -65,12 +65,12 @@ export const createDynamicMiddleware = < middlewareMap.set(entry.id, entry) }) }, - { withTypes: () => addMiddleware } + { withTypes: () => addMiddleware }, ) as AddMiddleware const getFinalMiddleware: Middleware<{}, State, Dispatch> = (api) => { const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => - emplace(entry.applied, api, { insert: () => entry.middleware(api) }) + emplace(entry.applied, api, { insert: () => entry.middleware(api) }), ) return compose(...appliedMiddleware) } diff --git a/packages/toolkit/src/dynamicMiddleware/react/index.ts b/packages/toolkit/src/dynamicMiddleware/react/index.ts index ed2c4d9fe3..83a8194606 100644 --- a/packages/toolkit/src/dynamicMiddleware/react/index.ts +++ b/packages/toolkit/src/dynamicMiddleware/react/index.ts @@ -23,23 +23,23 @@ import type { export type UseDispatchWithMiddlewareHook< Middlewares extends Middleware[] = [], State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > = () => TSHelpersExtractDispatchExtensions & Dispatch export type CreateDispatchWithMiddlewareHook< State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > = { < Middlewares extends [ Middleware, - ...Middleware[] - ] + ...Middleware[], + ], >( ...middlewares: Middlewares ): UseDispatchWithMiddlewareHook withTypes< - MiddlewareConfig extends MiddlewareApiConfig + MiddlewareConfig extends MiddlewareApiConfig, >(): CreateDispatchWithMiddlewareHook< GetState, GetDispatch @@ -51,12 +51,12 @@ type ActionFromDispatch> = interface ReactDynamicMiddlewareInstance< State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > extends DynamicMiddlewareInstance { createDispatchWithMiddlewareHookFactory: ( context?: Context< ReactReduxContextValue> - > + >, ) => CreateDispatchWithMiddlewareHook createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook< State, @@ -66,14 +66,14 @@ interface ReactDynamicMiddlewareInstance< export const createDynamicMiddleware = < State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, >(): ReactDynamicMiddlewareInstance => { const instance = cDM() const createDispatchWithMiddlewareHookFactory = ( // @ts-ignore context: Context< ReactReduxContextValue> - > = ReactReduxContext + > = ReactReduxContext, ) => { const useDispatch = // @ts-ignore @@ -81,7 +81,7 @@ export const createDynamicMiddleware = < ? useDefaultDispatch : createDispatchHook(context) function createDispatchWithMiddlewareHook< - Middlewares extends Middleware[] + Middlewares extends Middleware[], >(...middlewares: Middlewares) { instance.addMiddleware(...middlewares) return useDispatch diff --git a/packages/toolkit/src/dynamicMiddleware/tests/index.test-d.ts b/packages/toolkit/src/dynamicMiddleware/tests/index.test-d.ts index c34bc364b7..7273273530 100644 --- a/packages/toolkit/src/dynamicMiddleware/tests/index.test-d.ts +++ b/packages/toolkit/src/dynamicMiddleware/tests/index.test-d.ts @@ -37,15 +37,15 @@ describe('type tests', () => { typedInstance.addMiddleware( compatibleMiddleware, // @ts-expect-error - incompatibleMiddleware + incompatibleMiddleware, ) const dispatch = store.dispatch( typedInstance.withMiddleware( compatibleMiddleware, // @ts-expect-error - incompatibleMiddleware - ) + incompatibleMiddleware, + ), ) }) @@ -58,7 +58,7 @@ describe('type tests', () => { addMiddleware( compatibleMiddleware, // @ts-expect-error - incompatibleMiddleware + incompatibleMiddleware, ) const withMiddleware = untypedInstance.withMiddleware.withTypes<{ @@ -70,14 +70,14 @@ describe('type tests', () => { withMiddleware( compatibleMiddleware, // @ts-expect-error - incompatibleMiddleware - ) + incompatibleMiddleware, + ), ) }) test('withMiddleware returns typed dispatch, with any applicable extensions', () => { const dispatch = store.dispatch( - typedInstance.withMiddleware(addedMiddleware) + typedInstance.withMiddleware(addedMiddleware), ) // standard diff --git a/packages/toolkit/src/dynamicMiddleware/tests/index.test.ts b/packages/toolkit/src/dynamicMiddleware/tests/index.test.ts index 7f3e0885a2..5c97d834d3 100644 --- a/packages/toolkit/src/dynamicMiddleware/tests/index.test.ts +++ b/packages/toolkit/src/dynamicMiddleware/tests/index.test.ts @@ -20,7 +20,7 @@ const matchId = action.payload === id export const makeProbeableMiddleware = ( - id: Id + id: Id, ): Middleware<{ (action: PayloadAction): Id }> => { @@ -65,7 +65,7 @@ describe('createDynamicMiddleware', () => { expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2)) const dispatch = store.dispatch( - dynamicInstance.withMiddleware(makeProbeableMiddleware(2)) + dynamicInstance.withMiddleware(makeProbeableMiddleware(2)), ) expect(dispatch).toEqual(expect.any(Function)) diff --git a/packages/toolkit/src/dynamicMiddleware/tests/react.test-d.ts b/packages/toolkit/src/dynamicMiddleware/tests/react.test-d.ts index f7c8d6645a..ed8955fd2d 100644 --- a/packages/toolkit/src/dynamicMiddleware/tests/react.test-d.ts +++ b/packages/toolkit/src/dynamicMiddleware/tests/react.test-d.ts @@ -24,7 +24,7 @@ describe('type tests', () => { const useDispatch = typedInstance.createDispatchWithMiddlewareHook( compatibleMiddleware, // @ts-expect-error - incompatibleMiddleware + incompatibleMiddleware, ) const createDispatchWithMiddlewareHook = @@ -32,7 +32,7 @@ describe('type tests', () => { const useDispatchWithContext = createDispatchWithMiddlewareHook( compatibleMiddleware, // @ts-expect-error - incompatibleMiddleware + incompatibleMiddleware, ) }) @@ -45,7 +45,7 @@ describe('type tests', () => { const useDispatch = createDispatchWithMiddlewareHook( compatibleMiddleware, // @ts-expect-error - incompatibleMiddleware + incompatibleMiddleware, ) const createCustomDispatchWithMiddlewareHook = untypedInstance @@ -57,7 +57,7 @@ describe('type tests', () => { const useCustomDispatch = createCustomDispatchWithMiddlewareHook( compatibleMiddleware, // @ts-expect-error - incompatibleMiddleware + incompatibleMiddleware, ) }) diff --git a/packages/toolkit/src/dynamicMiddleware/tests/react.test.tsx b/packages/toolkit/src/dynamicMiddleware/tests/react.test.tsx index 86581586d2..546c1077f5 100644 --- a/packages/toolkit/src/dynamicMiddleware/tests/react.test.tsx +++ b/packages/toolkit/src/dynamicMiddleware/tests/react.test.tsx @@ -24,7 +24,7 @@ describe('createReactDynamicMiddleware', () => { expect(store.dispatch(probeMiddleware(1))).toBe(1) const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook( - makeProbeableMiddleware(2) + makeProbeableMiddleware(2), ) // injected @@ -40,7 +40,7 @@ describe('createReactDynamicMiddleware', () => { }) const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook( - makeProbeableMiddleware(2) + makeProbeableMiddleware(2), ) let dispatch: Dispatch | undefined @@ -77,7 +77,7 @@ describe('createReactDynamicMiddleware', () => { dynamicInstance.createDispatchWithMiddlewareHookFactory(context) const useDispatch = createDispatchWithMiddlewareHook( - makeProbeableMiddleware(2) + makeProbeableMiddleware(2), ) let dispatch: Dispatch | undefined diff --git a/packages/toolkit/src/dynamicMiddleware/types.ts b/packages/toolkit/src/dynamicMiddleware/types.ts index dc3d563c3c..70590afbcb 100644 --- a/packages/toolkit/src/dynamicMiddleware/types.ts +++ b/packages/toolkit/src/dynamicMiddleware/types.ts @@ -32,7 +32,7 @@ export type GetDispatch = MiddlewareApiConfig extends { export type AddMiddleware< State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > = { (...middlewares: Middleware[]): void withTypes(): AddMiddleware< @@ -43,7 +43,7 @@ export type AddMiddleware< export interface WithMiddleware< State = any, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > extends BaseActionCreator< Middleware[], 'dynamicMiddleware/add', @@ -61,13 +61,13 @@ export interface WithMiddleware< export interface DynamicDispatch { // return a version of dispatch that knows about middleware []>( - action: PayloadAction + action: PayloadAction, ): ExtractDispatchExtensions & this } export type MiddlewareEntry< State = unknown, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > = { id: string middleware: Middleware @@ -79,12 +79,12 @@ export type MiddlewareEntry< export type DynamicMiddleware< State = unknown, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > = Middleware export type DynamicMiddlewareInstance< State = unknown, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > = { middleware: DynamicMiddleware addMiddleware: AddMiddleware diff --git a/packages/toolkit/src/entities/create_adapter.ts b/packages/toolkit/src/entities/create_adapter.ts index 83ad6c6515..726ad82c32 100644 --- a/packages/toolkit/src/entities/create_adapter.ts +++ b/packages/toolkit/src/entities/create_adapter.ts @@ -34,7 +34,7 @@ export function createEntityAdapter( options: { selectId?: IdSelector sortComparer?: false | Comparer - } = {} + } = {}, ): EntityAdapter { const { selectId, sortComparer }: EntityDefinition = { sortComparer: false, diff --git a/packages/toolkit/src/entities/entity_state.ts b/packages/toolkit/src/entities/entity_state.ts index 62ab918442..6b0744cdee 100644 --- a/packages/toolkit/src/entities/entity_state.ts +++ b/packages/toolkit/src/entities/entity_state.ts @@ -13,7 +13,7 @@ export function getInitialEntityState(): EntityState< export function createInitialStateFactory() { function getInitialState(): EntityState function getInitialState( - additionalState: S + additionalState: S, ): EntityState & S function getInitialState(additionalState: any = {}): any { return Object.assign(getInitialEntityState(), additionalState) diff --git a/packages/toolkit/src/entities/models.ts b/packages/toolkit/src/entities/models.ts index 068dfc227d..a7ec0238d9 100644 --- a/packages/toolkit/src/entities/models.ts +++ b/packages/toolkit/src/entities/models.ts @@ -43,9 +43,11 @@ export interface EntityDefinition { export type PreventAny = CastAny< S, EntityState - > +> -export type DraftableEntityState = EntityState | Draft> +export type DraftableEntityState = + | EntityState + | Draft> /** * @public @@ -53,101 +55,103 @@ export type DraftableEntityState = EntityState | export interface EntityStateAdapter { addOne>( state: PreventAny, - entity: T + entity: T, ): S addOne>( state: PreventAny, - action: PayloadAction + action: PayloadAction, ): S addMany>( state: PreventAny, - entities: readonly T[] | Record + entities: readonly T[] | Record, ): S addMany>( state: PreventAny, - entities: PayloadAction> + entities: PayloadAction>, ): S setOne>( state: PreventAny, - entity: T + entity: T, ): S setOne>( state: PreventAny, - action: PayloadAction + action: PayloadAction, ): S setMany>( state: PreventAny, - entities: readonly T[] | Record + entities: readonly T[] | Record, ): S setMany>( state: PreventAny, - entities: PayloadAction> + entities: PayloadAction>, ): S setAll>( state: PreventAny, - entities: readonly T[] | Record + entities: readonly T[] | Record, ): S setAll>( state: PreventAny, - entities: PayloadAction> + entities: PayloadAction>, ): S removeOne>( state: PreventAny, - key: Id + key: Id, ): S removeOne>( state: PreventAny, - key: PayloadAction + key: PayloadAction, ): S removeMany>( state: PreventAny, - keys: readonly Id[] + keys: readonly Id[], ): S removeMany>( state: PreventAny, - keys: PayloadAction + keys: PayloadAction, ): S - removeAll>(state: PreventAny): S + removeAll>( + state: PreventAny, + ): S updateOne>( state: PreventAny, - update: Update + update: Update, ): S updateOne>( state: PreventAny, - update: PayloadAction> + update: PayloadAction>, ): S updateMany>( state: PreventAny, - updates: ReadonlyArray> + updates: ReadonlyArray>, ): S updateMany>( state: PreventAny, - updates: PayloadAction>> + updates: PayloadAction>>, ): S upsertOne>( state: PreventAny, - entity: T + entity: T, ): S upsertOne>( state: PreventAny, - entity: PayloadAction + entity: PayloadAction, ): S upsertMany>( state: PreventAny, - entities: readonly T[] | Record + entities: readonly T[] | Record, ): S upsertMany>( state: PreventAny, - entities: PayloadAction> + entities: PayloadAction>, ): S } @@ -173,10 +177,10 @@ export interface EntityAdapter getInitialState(state: S): EntityState & S getSelectors( selectState?: undefined, - options?: GetSelectorsOptions + options?: GetSelectorsOptions, ): EntitySelectors, Id> getSelectors( selectState: (state: V) => EntityState, - options?: GetSelectorsOptions + options?: GetSelectorsOptions, ): EntitySelectors } diff --git a/packages/toolkit/src/entities/sorted_state_adapter.ts b/packages/toolkit/src/entities/sorted_state_adapter.ts index 91645d1af0..1a2af5c527 100644 --- a/packages/toolkit/src/entities/sorted_state_adapter.ts +++ b/packages/toolkit/src/entities/sorted_state_adapter.ts @@ -4,7 +4,7 @@ import type { EntityStateAdapter, Update, EntityId, - DraftableEntityState + DraftableEntityState, } from './models' import { createStateOperator } from './state_adapter' import { createUnsortedStateAdapter } from './unsorted_state_adapter' @@ -16,7 +16,7 @@ import { export function createSortedStateAdapter( selectId: IdSelector, - sort: Comparer + sort: Comparer, ): EntityStateAdapter { type R = DraftableEntityState @@ -29,12 +29,12 @@ export function createSortedStateAdapter( function addManyMutably( newEntities: readonly T[] | Record, - state: R + state: R, ): void { newEntities = ensureEntitiesArray(newEntities) const models = newEntities.filter( - (model) => !(selectIdValue(model, selectId) in state.entities) + (model) => !(selectIdValue(model, selectId) in state.entities), ) if (models.length !== 0) { @@ -48,7 +48,7 @@ export function createSortedStateAdapter( function setManyMutably( newEntities: readonly T[] | Record, - state: R + state: R, ): void { newEntities = ensureEntitiesArray(newEntities) if (newEntities.length !== 0) { @@ -58,7 +58,7 @@ export function createSortedStateAdapter( function setAllMutably( newEntities: readonly T[] | Record, - state: R + state: R, ): void { newEntities = ensureEntitiesArray(newEntities) state.entities = {} as Record @@ -73,7 +73,7 @@ export function createSortedStateAdapter( function updateManyMutably( updates: ReadonlyArray>, - state: R + state: R, ): void { let appliedUpdates = false @@ -88,8 +88,8 @@ export function createSortedStateAdapter( Object.assign(entity, update.changes) const newId = selectId(entity) if (update.id !== newId) { - delete (state.entities as Record)[update.id]; - (state.entities as Record)[newId] = entity + delete (state.entities as Record)[update.id] + ;(state.entities as Record)[newId] = entity } } @@ -104,12 +104,12 @@ export function createSortedStateAdapter( function upsertManyMutably( newEntities: readonly T[] | Record, - state: R + state: R, ): void { const [added, updated] = splitAddedUpdatedEntities( newEntities, selectId, - state + state, ) updateManyMutably(updated, state) @@ -133,7 +133,7 @@ export function createSortedStateAdapter( function merge(models: readonly T[], state: R): void { // Insert/overwrite all new/updated models.forEach((model) => { - (state.entities as Record)[selectId(model)] = model + ;(state.entities as Record)[selectId(model)] = model }) resortEntities(state) diff --git a/packages/toolkit/src/entities/state_adapter.ts b/packages/toolkit/src/entities/state_adapter.ts index 93738d21c2..f13d3e3c90 100644 --- a/packages/toolkit/src/entities/state_adapter.ts +++ b/packages/toolkit/src/entities/state_adapter.ts @@ -1,34 +1,36 @@ import { produce as createNextState, isDraft } from 'immer' -import type { Draft } from 'immer' +import type { Draft } from 'immer' import type { EntityId, DraftableEntityState, PreventAny } from './models' import type { PayloadAction } from '../createAction' import { isFSA } from '../createAction' -export const isDraftTyped = isDraft as (value: T | Draft) => value is Draft +export const isDraftTyped = isDraft as ( + value: T | Draft, +) => value is Draft export function createSingleArgumentStateOperator( - mutator: (state: DraftableEntityState) => void + mutator: (state: DraftableEntityState) => void, ) { const operator = createStateOperator( - (_: undefined, state: DraftableEntityState) => mutator(state) + (_: undefined, state: DraftableEntityState) => mutator(state), ) return function operation>( - state: PreventAny + state: PreventAny, ): S { return operator(state as S, undefined) } } export function createStateOperator( - mutator: (arg: R, state: DraftableEntityState) => void + mutator: (arg: R, state: DraftableEntityState) => void, ) { return function operation>( state: S, - arg: R | PayloadAction + arg: R | PayloadAction, ): S { function isPayloadActionArgument( - arg: R | PayloadAction + arg: R | PayloadAction, ): arg is PayloadAction { return isFSA(arg) } @@ -50,7 +52,7 @@ export function createStateOperator( // since it's a draft, we'll just return it return state } - + return createNextState(state, runMutator) } } diff --git a/packages/toolkit/src/entities/state_selectors.ts b/packages/toolkit/src/entities/state_selectors.ts index f8f04449df..bd64cf001b 100644 --- a/packages/toolkit/src/entities/state_selectors.ts +++ b/packages/toolkit/src/entities/state_selectors.ts @@ -15,17 +15,19 @@ export interface GetSelectorsOptions { export function createSelectorsFactory() { function getSelectors( selectState?: undefined, - options?: GetSelectorsOptions + options?: GetSelectorsOptions, ): EntitySelectors, Id> function getSelectors( selectState: (state: V) => EntityState, - options?: GetSelectorsOptions + options?: GetSelectorsOptions, ): EntitySelectors function getSelectors( selectState?: (state: V) => EntityState, - options: GetSelectorsOptions = {} + options: GetSelectorsOptions = {}, ): EntitySelectors { - const { createSelector = createDraftSafeSelector as AnyCreateSelectorFunction } = options + const { + createSelector = createDraftSafeSelector as AnyCreateSelectorFunction, + } = options const selectIds = (state: EntityState) => state.ids @@ -34,7 +36,7 @@ export function createSelectorsFactory() { const selectAll = createSelector( selectIds, selectEntities, - (ids, entities): T[] => ids.map((id) => entities[id]!) + (ids, entities): T[] => ids.map((id) => entities[id]!), ) const selectId = (_: unknown, id: Id) => id @@ -55,7 +57,7 @@ export function createSelectorsFactory() { const selectGlobalizedEntities = createSelector( selectState as Selector>, - selectEntities + selectEntities, ) return { @@ -66,7 +68,7 @@ export function createSelectorsFactory() { selectById: createSelector( selectGlobalizedEntities, selectId, - selectById + selectById, ), } } diff --git a/packages/toolkit/src/entities/tests/entity_slice_enhancer.test.ts b/packages/toolkit/src/entities/tests/entity_slice_enhancer.test.ts index 9e8e380815..0842a20505 100644 --- a/packages/toolkit/src/entities/tests/entity_slice_enhancer.test.ts +++ b/packages/toolkit/src/entities/tests/entity_slice_enhancer.test.ts @@ -1,15 +1,20 @@ -import { createEntityAdapter, createSlice } from "../.."; -import type { PayloadAction, Slice, SliceCaseReducers, UnknownAction } from "../.."; -import type { EntityId, EntityState, IdSelector } from "../models"; -import type { BookModel } from "./fixtures/book"; +import { createEntityAdapter, createSlice } from '../..' +import type { + PayloadAction, + Slice, + SliceCaseReducers, + UnknownAction, +} from '../..' +import type { EntityId, EntityState, IdSelector } from '../models' +import type { BookModel } from './fixtures/book' describe('Entity Slice Enhancer', () => { - let slice: Slice>; + let slice: Slice> beforeEach(() => { const indieSlice = entitySliceEnhancer({ name: 'book', - selectId: (book: BookModel) => book.id + selectId: (book: BookModel) => book.id, }) slice = indieSlice }) @@ -18,7 +23,7 @@ describe('Entity Slice Enhancer', () => { const book = { id: '0', title: 'Der Steppenwolf', - author: 'Herman Hesse' + author: 'Herman Hesse', } const action = slice.actions.oneAdded(book) const oneAdded = slice.reducer(undefined, action as UnknownAction) @@ -35,23 +40,20 @@ interface EntitySliceArgs { function entitySliceEnhancer({ name, selectId, - modelReducer + modelReducer, }: EntitySliceArgs) { const modelAdapter = createEntityAdapter({ - selectId - }); + selectId, + }) return createSlice({ name, initialState: modelAdapter.getInitialState(), reducers: { oneAdded(state, action: PayloadAction) { - modelAdapter.addOne( - state, - action.payload - ) + modelAdapter.addOne(state, action.payload) }, - ...modelReducer - } + ...modelReducer, + }, }) } diff --git a/packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts b/packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts index ff691a8326..9683715fb8 100644 --- a/packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts +++ b/packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts @@ -360,7 +360,7 @@ describe('Sorted State Adapter', () => { { id: 'C', order: 3, ts: 0 }, { id: 'D', order: 3, ts: 0 }, { id: 'E', order: 3, ts: 0 }, - ] + ], ) const updated = sortedItemsAdapter.updateOne(withInitialItems, { diff --git a/packages/toolkit/src/entities/tests/state_selectors.test.ts b/packages/toolkit/src/entities/tests/state_selectors.test.ts index f581965be3..3afba41ac6 100644 --- a/packages/toolkit/src/entities/tests/state_selectors.test.ts +++ b/packages/toolkit/src/entities/tests/state_selectors.test.ts @@ -132,7 +132,7 @@ describe('Entity State Selectors', () => { it('should use the custom createSelector function if provided', () => { const memoizeSpy = vi.fn( // test that we're allowed to pass memoizers with different options, as long as they're optional - any>(fn: F, param?: boolean) => fn + any>(fn: F, param?: boolean) => fn, ) const createCustomSelector = createDraftSafeSelectorCreator(memoizeSpy) diff --git a/packages/toolkit/src/entities/unsorted_state_adapter.ts b/packages/toolkit/src/entities/unsorted_state_adapter.ts index 1b74a01479..e2d6c31357 100644 --- a/packages/toolkit/src/entities/unsorted_state_adapter.ts +++ b/packages/toolkit/src/entities/unsorted_state_adapter.ts @@ -4,7 +4,7 @@ import type { IdSelector, Update, EntityId, - DraftableEntityState + DraftableEntityState, } from './models' import { createStateOperator, @@ -17,7 +17,7 @@ import { } from './utils' export function createUnsortedStateAdapter( - selectId: IdSelector + selectId: IdSelector, ): EntityStateAdapter { type R = DraftableEntityState @@ -28,13 +28,13 @@ export function createUnsortedStateAdapter( return } - state.ids.push(key as Id & Draft); - (state.entities as Record)[key] = entity + state.ids.push(key as Id & Draft) + ;(state.entities as Record)[key] = entity } function addManyMutably( newEntities: readonly T[] | Record, - state: R + state: R, ): void { newEntities = ensureEntitiesArray(newEntities) @@ -46,14 +46,14 @@ export function createUnsortedStateAdapter( function setOneMutably(entity: T, state: R): void { const key = selectIdValue(entity, selectId) if (!(key in state.entities)) { - state.ids.push(key as Id & Draft); + state.ids.push(key as Id & Draft) } - (state.entities as Record)[key] = entity + ;(state.entities as Record)[key] = entity } function setManyMutably( newEntities: readonly T[] | Record, - state: R + state: R, ): void { newEntities = ensureEntitiesArray(newEntities) for (const entity of newEntities) { @@ -63,7 +63,7 @@ export function createUnsortedStateAdapter( function setAllMutably( newEntities: readonly T[] | Record, - state: R + state: R, ): void { newEntities = ensureEntitiesArray(newEntities) @@ -88,7 +88,9 @@ export function createUnsortedStateAdapter( }) if (didMutate) { - state.ids = (state.ids as Id[]).filter((id) => id in state.entities) as Id[] | Draft + state.ids = (state.ids as Id[]).filter((id) => id in state.entities) as + | Id[] + | Draft } } @@ -102,7 +104,7 @@ export function createUnsortedStateAdapter( function takeNewKey( keys: { [id: string]: Id }, update: Update, - state: R + state: R, ): boolean { const original: T | undefined = (state.entities as Record)[update.id] if (original === undefined) { @@ -117,7 +119,7 @@ export function createUnsortedStateAdapter( delete (state.entities as Record)[update.id] } - (state.entities as Record)[newKey] = updated + ;(state.entities as Record)[newKey] = updated return hasNewKey } @@ -128,7 +130,7 @@ export function createUnsortedStateAdapter( function updateManyMutably( updates: ReadonlyArray>, - state: R + state: R, ): void { const newKeys: { [id: string]: Id } = {} @@ -163,7 +165,7 @@ export function createUnsortedStateAdapter( if (didMutateIds) { state.ids = Object.values(state.entities).map((e) => - selectIdValue(e as T, selectId) + selectIdValue(e as T, selectId), ) } } @@ -175,12 +177,12 @@ export function createUnsortedStateAdapter( function upsertManyMutably( newEntities: readonly T[] | Record, - state: R + state: R, ): void { const [added, updated] = splitAddedUpdatedEntities( newEntities, selectId, - state + state, ) updateManyMutably(updated, state) diff --git a/packages/toolkit/src/entities/utils.ts b/packages/toolkit/src/entities/utils.ts index 71435e3a01..5e3fb92fc1 100644 --- a/packages/toolkit/src/entities/utils.ts +++ b/packages/toolkit/src/entities/utils.ts @@ -1,8 +1,13 @@ -import type { IdSelector, Update, EntityId, DraftableEntityState } from './models' +import type { + IdSelector, + Update, + EntityId, + DraftableEntityState, +} from './models' export function selectIdValue( entity: T, - selectId: IdSelector + selectId: IdSelector, ) { const key = selectId(entity) @@ -13,7 +18,7 @@ export function selectIdValue( 'The entity that was passed:', entity, 'The `selectId` implementation:', - selectId.toString() + selectId.toString(), ) } @@ -21,7 +26,7 @@ export function selectIdValue( } export function ensureEntitiesArray( - entities: readonly T[] | Record + entities: readonly T[] | Record, ): readonly T[] { if (!Array.isArray(entities)) { entities = Object.values(entities) @@ -33,7 +38,7 @@ export function ensureEntitiesArray( export function splitAddedUpdatedEntities( newEntities: readonly T[] | Record, selectId: IdSelector, - state: DraftableEntityState + state: DraftableEntityState, ): [T[], Update[]] { newEntities = ensureEntitiesArray(newEntities) diff --git a/packages/toolkit/src/getDefaultEnhancers.ts b/packages/toolkit/src/getDefaultEnhancers.ts index 6d13646482..bfc3a3aa57 100644 --- a/packages/toolkit/src/getDefaultEnhancers.ts +++ b/packages/toolkit/src/getDefaultEnhancers.ts @@ -10,11 +10,11 @@ type GetDefaultEnhancersOptions = { } export type GetDefaultEnhancers> = ( - options?: GetDefaultEnhancersOptions + options?: GetDefaultEnhancersOptions, ) => Tuple<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions }>]> export const buildGetDefaultEnhancers = >( - middlewareEnhancer: StoreEnhancer<{ dispatch: ExtractDispatchExtensions }> + middlewareEnhancer: StoreEnhancer<{ dispatch: ExtractDispatchExtensions }>, ): GetDefaultEnhancers => function getDefaultEnhancers(options) { const { autoBatch = true } = options ?? {} @@ -22,7 +22,9 @@ export const buildGetDefaultEnhancers = >( let enhancerArray = new Tuple(middlewareEnhancer) if (autoBatch) { enhancerArray.push( - autoBatchEnhancer(typeof autoBatch === 'object' ? autoBatch : undefined) + autoBatchEnhancer( + typeof autoBatch === 'object' ? autoBatch : undefined, + ), ) } return enhancerArray as any diff --git a/packages/toolkit/src/getDefaultMiddleware.ts b/packages/toolkit/src/getDefaultMiddleware.ts index 6ec507b4ce..95464ceb98 100644 --- a/packages/toolkit/src/getDefaultMiddleware.ts +++ b/packages/toolkit/src/getDefaultMiddleware.ts @@ -30,14 +30,14 @@ interface GetDefaultMiddlewareOptions { export type ThunkMiddlewareFor< S, - O extends GetDefaultMiddlewareOptions = {} + O extends GetDefaultMiddlewareOptions = {}, > = O extends { thunk: false } ? never : O extends { thunk: { extraArgument: infer E } } - ? ThunkMiddleware - : ThunkMiddleware + ? ThunkMiddleware + : ThunkMiddleware export type GetDefaultMiddleware = < O extends GetDefaultMiddlewareOptions = { @@ -45,9 +45,9 @@ export type GetDefaultMiddleware = < immutableCheck: true serializableCheck: true actionCreatorCheck: true - } + }, >( - options?: O + options?: O, ) => Tuple], never>> export const buildGetDefaultMiddleware = (): GetDefaultMiddleware => @@ -79,7 +79,7 @@ export const buildGetDefaultMiddleware = (): GetDefaultMiddleware => } middlewareArray.unshift( - createImmutableStateInvariantMiddleware(immutableOptions) + createImmutableStateInvariantMiddleware(immutableOptions), ) /* PROD_STOP_REMOVE_UMD */ } @@ -93,7 +93,7 @@ export const buildGetDefaultMiddleware = (): GetDefaultMiddleware => } middlewareArray.push( - createSerializableStateInvariantMiddleware(serializableOptions) + createSerializableStateInvariantMiddleware(serializableOptions), ) } if (actionCreatorCheck) { @@ -104,7 +104,7 @@ export const buildGetDefaultMiddleware = (): GetDefaultMiddleware => } middlewareArray.unshift( - createActionCreatorInvariantMiddleware(actionCreatorOptions) + createActionCreatorInvariantMiddleware(actionCreatorOptions), ) } } diff --git a/packages/toolkit/src/immutableStateInvariantMiddleware.ts b/packages/toolkit/src/immutableStateInvariantMiddleware.ts index 90f3a8ebe1..84fc782f56 100644 --- a/packages/toolkit/src/immutableStateInvariantMiddleware.ts +++ b/packages/toolkit/src/immutableStateInvariantMiddleware.ts @@ -15,7 +15,7 @@ export function isImmutableDefault(value: unknown): boolean { export function trackForMutations( isImmutable: IsImmutableFunc, ignorePaths: IgnorePaths | undefined, - obj: any + obj: any, ) { const trackedProperties = trackProperties(isImmutable, ignorePaths, obj) return { @@ -35,7 +35,7 @@ function trackProperties( ignorePaths: IgnorePaths = [], obj: Record, path: string = '', - checkedObjects: Set> = new Set() + checkedObjects: Set> = new Set(), ) { const tracked: Partial = { value: obj } @@ -53,7 +53,7 @@ function trackProperties( isImmutable, ignorePaths, obj[key], - childPath + childPath, ) } } @@ -68,7 +68,7 @@ function detectMutations( trackedProperty: TrackedProperty, obj: any, sameParentRef: boolean = false, - path: string = '' + path: string = '', ): { wasMutated: boolean; path?: string } { const prevObj = trackedProperty ? trackedProperty.value : undefined @@ -114,7 +114,7 @@ function detectMutations( trackedProperty.children[key], obj[key], sameRef, - nestedPath + nestedPath, ) if (result.wasMutated) { @@ -159,7 +159,7 @@ export interface ImmutableStateInvariantMiddlewareOptions { * @public */ export function createImmutableStateInvariantMiddleware( - options: ImmutableStateInvariantMiddlewareOptions = {} + options: ImmutableStateInvariantMiddlewareOptions = {}, ): Middleware { if (process.env.NODE_ENV === 'production') { return () => (next) => (action) => next(action) @@ -168,14 +168,14 @@ export function createImmutableStateInvariantMiddleware( obj: any, serializer?: EntryProcessor, indent?: string | number, - decycler?: EntryProcessor + decycler?: EntryProcessor, ): string { return JSON.stringify(obj, getSerialize(serializer, decycler), indent) } function getSerialize( serializer?: EntryProcessor, - decycler?: EntryProcessor + decycler?: EntryProcessor, ): EntryProcessor { let stack: any[] = [], keys: any[] = [] @@ -216,7 +216,7 @@ export function createImmutableStateInvariantMiddleware( return (next) => (action) => { const measureUtils = getTimeMeasureUtils( warnAfter, - 'ImmutableStateInvariantMiddleware' + 'ImmutableStateInvariantMiddleware', ) measureUtils.measureTime(() => { @@ -230,7 +230,7 @@ export function createImmutableStateInvariantMiddleware( throw new Error( `A state mutation was detected between dispatches, in the path '${ result.path || '' - }'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)` + }'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`, ) } }) @@ -249,8 +249,8 @@ export function createImmutableStateInvariantMiddleware( `A state mutation was detected inside a dispatch, in the path: ${ result.path || '' }. Take a look at the reducer(s) handling the action ${stringify( - action - )}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)` + action, + )}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`, ) } }) diff --git a/packages/toolkit/src/index.ts b/packages/toolkit/src/index.ts index 1c8d41af43..6c94d1df0c 100644 --- a/packages/toolkit/src/index.ts +++ b/packages/toolkit/src/index.ts @@ -203,6 +203,9 @@ export { combineSlices } from './combineSlices' export type { WithSlice } from './combineSlices' -export type { ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, SafePromise } from './tsHelpers' +export type { + ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, + SafePromise, +} from './tsHelpers' export { formatProdErrorMessage } from './formatProdErrorMessage' diff --git a/packages/toolkit/src/listenerMiddleware/index.ts b/packages/toolkit/src/listenerMiddleware/index.ts index e87a53f256..03d68eba0d 100644 --- a/packages/toolkit/src/listenerMiddleware/index.ts +++ b/packages/toolkit/src/listenerMiddleware/index.ts @@ -84,16 +84,16 @@ const alm = 'listenerMiddleware' as const const createFork = ( parentAbortSignal: AbortSignalWithReason, - parentBlockingPromises: Promise[] + parentBlockingPromises: Promise[], ) => { const linkControllers = (controller: AbortController) => addAbortSignalListener(parentAbortSignal, () => - abortControllerWithReason(controller, parentAbortSignal.reason) + abortControllerWithReason(controller, parentAbortSignal.reason), ) return ( taskExecutor: ForkedTaskExecutor, - opts?: ForkOptions + opts?: ForkOptions, ): ForkedTask => { assertFunction(taskExecutor, 'taskExecutor') const childAbortController = new AbortController() @@ -112,7 +112,7 @@ const createFork = ( validateActive(childAbortController.signal) return result }, - () => abortControllerWithReason(childAbortController, taskCompleted) + () => abortControllerWithReason(childAbortController, taskCompleted), ) if (opts?.autoJoin) { @@ -130,7 +130,7 @@ const createFork = ( const createTakePattern = ( startListening: AddListenerOverloads, - signal: AbortSignal + signal: AbortSignal, ): TakePattern => { /** * A function that takes a ListenerPredicate and an optional timeout, @@ -141,7 +141,7 @@ const createTakePattern = ( */ const take = async

>( predicate: P, - timeout: number | undefined + timeout: number | undefined, ) => { validateActive(signal) @@ -173,7 +173,7 @@ const createTakePattern = ( if (timeout != null) { promises.push( - new Promise((resolve) => setTimeout(resolve, timeout, null)) + new Promise((resolve) => setTimeout(resolve, timeout, null)), ) } @@ -206,7 +206,7 @@ const getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => { // pass } else { throw new Error( - 'Creating or removing a listener requires one of the known fields for matching an action' + 'Creating or removing a listener requires one of the known fields for matching an action', ) } @@ -235,11 +235,11 @@ export const createListenerEntry: TypedCreateListenerEntry = return entry }, - { withTypes: () => createListenerEntry } + { withTypes: () => createListenerEntry }, ) as unknown as TypedCreateListenerEntry const cancelActiveListeners = ( - entry: ListenerEntry> + entry: ListenerEntry>, ) => { entry.pending.forEach((controller) => { abortControllerWithReason(controller, listenerCancelled) @@ -247,7 +247,7 @@ const cancelActiveListeners = ( } const createClearListenerMiddleware = ( - listenerMap: Map + listenerMap: Map, ) => { return () => { listenerMap.forEach(cancelActiveListeners) @@ -266,7 +266,7 @@ const createClearListenerMiddleware = ( const safelyNotifyError = ( errorHandler: ListenerErrorHandler, errorToNotify: unknown, - errorInfo: ListenerErrorInfo + errorInfo: ListenerErrorInfo, ): void => { try { errorHandler(errorToNotify, errorInfo) @@ -312,9 +312,9 @@ export const createListenerMiddleware = < unknown, UnknownAction >, - ExtraArgument = unknown + ExtraArgument = unknown, >( - middlewareOptions: CreateListenerMiddlewareOptions = {} + middlewareOptions: CreateListenerMiddlewareOptions = {}, ) => { const listenerMap = new Map() const { extra, onError = defaultErrorHandler } = middlewareOptions @@ -336,7 +336,7 @@ export const createListenerMiddleware = < const startListening = ((options: FallbackAddListenerOptions) => { let entry = find( Array.from(listenerMap.values()), - (existingEntry) => existingEntry.effect === options.effect + (existingEntry) => existingEntry.effect === options.effect, ) if (!entry) { @@ -351,7 +351,7 @@ export const createListenerMiddleware = < }) const stopListening = ( - options: FallbackAddListenerOptions & UnsubscribeListenerOptions + options: FallbackAddListenerOptions & UnsubscribeListenerOptions, ): boolean => { const { type, effect, predicate } = getListenerEntryPropsFrom(options) @@ -382,12 +382,12 @@ export const createListenerMiddleware = < entry: ListenerEntry>, action: unknown, api: MiddlewareAPI, - getOriginalState: () => StateType + getOriginalState: () => StateType, ) => { const internalTaskController = new AbortController() const take = createTakePattern( startListening as AddListenerOverloads, - internalTaskController.signal + internalTaskController.signal, ) const autoJoinPromises: Promise[] = [] @@ -401,7 +401,7 @@ export const createListenerMiddleware = < getOriginalState, condition: ( predicate: AnyListenerPredicate, - timeout?: number + timeout?: number, ) => take(predicate, timeout).then(Boolean), take, delay: createDelay(internalTaskController.signal), @@ -424,15 +424,15 @@ export const createListenerMiddleware = < cancel: () => { abortControllerWithReason( internalTaskController, - listenerCancelled + listenerCancelled, ) entry.pending.delete(internalTaskController) }, throwIfCancelled: () => { validateActive(internalTaskController.signal) }, - }) - ) + }), + ), ) } catch (listenerError) { if (!(listenerError instanceof TaskAbortError)) { @@ -450,79 +450,82 @@ export const createListenerMiddleware = < const clearListenerMiddleware = createClearListenerMiddleware(listenerMap) - const middleware: ListenerMiddleware = - (api) => (next) => (action) => { - if (!isAction(action)) { - // we only want to notify listeners for action objects - return next(action) - } - - if (addListener.match(action)) { - return startListening(action.payload as any) - } + const middleware: ListenerMiddleware< + StateType, + DispatchType, + ExtraArgument + > = (api) => (next) => (action) => { + if (!isAction(action)) { + // we only want to notify listeners for action objects + return next(action) + } - if (clearAllListeners.match(action)) { - clearListenerMiddleware() - return - } + if (addListener.match(action)) { + return startListening(action.payload as any) + } - if (removeListener.match(action)) { - return stopListening(action.payload) - } + if (clearAllListeners.match(action)) { + clearListenerMiddleware() + return + } - // Need to get this state _before_ the reducer processes the action - let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState() + if (removeListener.match(action)) { + return stopListening(action.payload) + } - // `getOriginalState` can only be called synchronously. - // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820 - const getOriginalState = (): StateType => { - if (originalState === INTERNAL_NIL_TOKEN) { - throw new Error( - `${alm}: getOriginalState can only be called synchronously` - ) - } + // Need to get this state _before_ the reducer processes the action + let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState() - return originalState as StateType + // `getOriginalState` can only be called synchronously. + // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820 + const getOriginalState = (): StateType => { + if (originalState === INTERNAL_NIL_TOKEN) { + throw new Error( + `${alm}: getOriginalState can only be called synchronously`, + ) } - let result: unknown - - try { - // Actually forward the action to the reducer before we handle listeners - result = next(action) - - if (listenerMap.size > 0) { - const currentState = api.getState() - // Work around ESBuild+TS transpilation issue - const listenerEntries = Array.from(listenerMap.values()) - for (const entry of listenerEntries) { - let runListener = false - - try { - runListener = entry.predicate(action, currentState, originalState) - } catch (predicateError) { - runListener = false + return originalState as StateType + } - safelyNotifyError(onError, predicateError, { - raisedBy: 'predicate', - }) - } + let result: unknown - if (!runListener) { - continue - } + try { + // Actually forward the action to the reducer before we handle listeners + result = next(action) + + if (listenerMap.size > 0) { + const currentState = api.getState() + // Work around ESBuild+TS transpilation issue + const listenerEntries = Array.from(listenerMap.values()) + for (const entry of listenerEntries) { + let runListener = false + + try { + runListener = entry.predicate(action, currentState, originalState) + } catch (predicateError) { + runListener = false + + safelyNotifyError(onError, predicateError, { + raisedBy: 'predicate', + }) + } - notifyListener(entry, action, api, getOriginalState) + if (!runListener) { + continue } + + notifyListener(entry, action, api, getOriginalState) } - } finally { - // Remove `originalState` store from this scope. - originalState = INTERNAL_NIL_TOKEN } - - return result + } finally { + // Remove `originalState` store from this scope. + originalState = INTERNAL_NIL_TOKEN } + return result + } + return { middleware, startListening, diff --git a/packages/toolkit/src/listenerMiddleware/task.ts b/packages/toolkit/src/listenerMiddleware/task.ts index 01f20a72c2..a2fffce0d9 100644 --- a/packages/toolkit/src/listenerMiddleware/task.ts +++ b/packages/toolkit/src/listenerMiddleware/task.ts @@ -22,7 +22,7 @@ export const validateActive = (signal: AbortSignal): void => { */ export function raceWithSignal( signal: AbortSignalWithReason, - promise: Promise + promise: Promise, ): Promise { let cleanup = noop return new Promise((resolve, reject) => { @@ -50,7 +50,7 @@ export function raceWithSignal( */ export const runTask = async ( task: () => Promise, - cleanUp?: () => void + cleanUp?: () => void, ): Promise> => { try { await Promise.resolve() @@ -82,7 +82,7 @@ export const createPause = (signal: AbortSignal) => { raceWithSignal(signal, promise).then((output) => { validateActive(signal) return output - }) + }), ) } } diff --git a/packages/toolkit/src/listenerMiddleware/tests/fork.test.ts b/packages/toolkit/src/listenerMiddleware/tests/fork.test.ts index 41a5df123f..98e0c68461 100644 --- a/packages/toolkit/src/listenerMiddleware/tests/fork.test.ts +++ b/packages/toolkit/src/listenerMiddleware/tests/fork.test.ts @@ -123,7 +123,7 @@ describe('fork', () => { }) .result.then( deferredForkedTaskError.resolve, - deferredForkedTaskError.resolve + deferredForkedTaskError.resolve, ) }, }) @@ -132,7 +132,7 @@ describe('fork', () => { store.dispatch(increment()) expect(await deferredForkedTaskError).toEqual( - new TaskAbortError(listenerCancelled) + new TaskAbortError(listenerCancelled), ) }) @@ -346,7 +346,7 @@ describe('fork', () => { store.dispatch(increment()) expect(await deferredResult).toEqual( - new TaskAbortError(listenerCancelled) + new TaskAbortError(listenerCancelled), ) }) @@ -383,13 +383,13 @@ describe('fork', () => { async (forkApi) => { forkApi.signal.addEventListener('abort', () => { deferredResult.resolve( - (forkApi.signal as AbortSignalWithReason).reason + (forkApi.signal as AbortSignalWithReason).reason, ) }) await forkApi.delay(10) }, - { autoJoin } + { autoJoin }, ) }, }) @@ -402,7 +402,7 @@ describe('fork', () => { if (cancelListener) unsubscribe({ cancelActive: true }) expect(await deferredResult).toBe(expectedAbortReason) - } + }, ) test('fork.delay does not trigger unhandledRejections for completed or cancelled tasks', async () => { @@ -418,7 +418,7 @@ describe('fork', () => { forkApi.signal.addEventListener( 'abort', deferredCompletedEvt.resolve, - { once: true } + { once: true }, ) forkApi.delay(100) // missing await @@ -433,7 +433,7 @@ describe('fork', () => { forkApi.signal.addEventListener( 'abort', deferredCompletedEvt.resolve, - { once: true } + { once: true }, ) forkApi.delay(1_000) // missing await await forkApi.pause(godotPauseTrigger) diff --git a/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts b/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts index 97bfbb50d2..56939af639 100644 --- a/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts +++ b/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts @@ -218,16 +218,16 @@ describe('createListenerMiddleware', () => { removeTypedListenerAction({ actionCreator: testAction2, effect, - }) - ) + }), + ), ).toBe(false) expect( store.dispatch( removeTypedListenerAction({ actionCreator: testAction1, effect, - }) - ) + }), + ), ).toBe(true) }) @@ -238,7 +238,7 @@ describe('createListenerMiddleware', () => { addListener({ type: testAction2.type, effect, - }) + }), ) store.dispatch(testAction2('b')) @@ -383,7 +383,7 @@ describe('createListenerMiddleware', () => { addListener({ actionCreator: testAction1, effect, - }) + }), ) store.dispatch(testAction1('a')) @@ -403,7 +403,7 @@ describe('createListenerMiddleware', () => { addListener({ actionCreator: testAction1, effect, - }) + }), ) store.dispatch(testAction1('a')) @@ -504,7 +504,7 @@ describe('createListenerMiddleware', () => { actionCreator: testAction1, effect, cancelActive: true, - }) + }), ) expect(wasCancelled).toBe(false) await delay(10) @@ -520,7 +520,7 @@ describe('createListenerMiddleware', () => { typeof store.dispatch >, 'effect' | 'withTypes' - > + >, ][] = [ ['predicate', { predicate: () => true }], ['actionCreator', { actionCreator: testAction1 }], @@ -546,7 +546,7 @@ describe('createListenerMiddleware', () => { store.dispatch(testAction1('b')) expect(effect).toBeCalledTimes(1) - } + }, ) const unforwardedActions: [string, UnknownAction][] = [ @@ -572,7 +572,7 @@ describe('createListenerMiddleware', () => { [{}, testAction1('a')], [{}, testAction2('b')], ]) - } + }, ) test('listenerApi.signal has correct reason when listener is cancelled or completes', async () => { @@ -586,7 +586,7 @@ describe('createListenerMiddleware', () => { () => { payload.resolve((signal as AbortSignalWithReason).reason) }, - { once: true } + { once: true }, ) cancelActiveListeners() @@ -595,10 +595,10 @@ describe('createListenerMiddleware', () => { }) const deferredCancelledSignalReason = store.dispatch( - notifyDeferred(deferred()) + notifyDeferred(deferred()), ).payload const deferredCompletedSignalReason = store.dispatch( - notifyDeferred(deferred()) + notifyDeferred(deferred()), ).payload expect(await deferredCancelledSignalReason).toBe(listenerCancelled) @@ -616,7 +616,7 @@ describe('createListenerMiddleware', () => { () => { payload.resolve((signal as AbortSignalWithReason).reason) }, - { once: true } + { once: true }, ) cancel() @@ -624,7 +624,7 @@ describe('createListenerMiddleware', () => { }) const deferredCancelledSignalReason = store.dispatch( - notifyDeferred(deferred()) + notifyDeferred(deferred()), ).payload expect(await deferredCancelledSignalReason).toBe(listenerCancelled) @@ -672,7 +672,7 @@ describe('createListenerMiddleware', () => { expect(listenerCompleted).toBe(false) expect(listenerCancelled).toBe(true) expect((error as any)?.message).toBe( - 'task cancelled (reason: listener-cancelled)' + 'task cancelled (reason: listener-cancelled)', ) }) @@ -682,7 +682,7 @@ describe('createListenerMiddleware', () => { if (action.payload === 'b') { api.unsubscribe() } - } + }, ) startListening({ @@ -745,7 +745,7 @@ describe('createListenerMiddleware', () => { listenerApi.signal.addEventListener( 'abort', () => listener1Test.resolve(listener1Calls), - { once: true } + { once: true }, ) await listenerApi.condition(() => true) listener1Test.reject(new Error('unreachable: listener1Test')) @@ -788,7 +788,7 @@ describe('createListenerMiddleware', () => { listenerApi.signal.addEventListener( 'abort', () => listener1Test.resolve(listener1Calls), - { once: true } + { once: true }, ) await listenerApi.condition(() => true) listener1Test.reject(new Error('unreachable: listener1Test')) @@ -895,8 +895,8 @@ describe('createListenerMiddleware', () => { const runIncrementBy = () => { listenerApi.dispatch( counterSlice.actions.incrementByAmount( - listenerApi.getOriginalState().value + 2 - ) + listenerApi.getOriginalState().value + 2, + ), ) } @@ -918,9 +918,9 @@ describe('createListenerMiddleware', () => { expect(onError).toBeCalledWith( new Error( - 'listenerMiddleware: getOriginalState can only be called synchronously' + 'listenerMiddleware: getOriginalState can only be called synchronously', ), - { raisedBy: 'effect' } + { raisedBy: 'effect' }, ) expect(store.getState()).toEqual({ value: 3 }) }) @@ -954,7 +954,7 @@ describe('createListenerMiddleware', () => { listenerApi.signal.addEventListener( 'abort', deferredCompletedEvt.resolve, - { once: true } + { once: true }, ) listenerApi.delay(100) // missing await }, @@ -967,7 +967,7 @@ describe('createListenerMiddleware', () => { listenerApi.signal.addEventListener( 'abort', deferredCancelledEvt.resolve, - { once: true } + { once: true }, ) listenerApi.delay(100) // missing await listenerApi.pause(godotPauseTrigger) @@ -1286,7 +1286,7 @@ describe('createListenerMiddleware', () => { listenerApi.unsubscribe() // run once listenerApi.signal.addEventListener( 'abort', - deferredCompletedEvt.resolve + deferredCompletedEvt.resolve, ) listenerApi.take(() => true) // missing await }, @@ -1298,7 +1298,7 @@ describe('createListenerMiddleware', () => { listenerApi.cancelActiveListeners() listenerApi.signal.addEventListener( 'abort', - deferredCancelledEvt.resolve + deferredCancelledEvt.resolve, ) listenerApi.take(() => true) // missing await await listenerApi.pause(godotPauseTrigger) diff --git a/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts b/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts index 3d6a3d1775..6756144579 100644 --- a/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts +++ b/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts @@ -36,7 +36,7 @@ export const counterSlice = createSlice({ export function fetchCount(amount = 1) { return new Promise<{ data: number }>((resolve) => - setTimeout(() => resolve({ data: amount }), 500) + setTimeout(() => resolve({ data: amount }), 500), ) } @@ -46,7 +46,7 @@ export const incrementAsync = createAsyncThunk( const response = await fetchCount(amount) // The value we return becomes the `fulfilled` action payload return response.data - } + }, ) const { increment } = counterSlice.actions @@ -127,7 +127,7 @@ describe('listenerMiddleware.withTypes()', () => { expectTypeOf(listenerApi.dispatch).toEqualTypeOf() }, - }) + }), ) }) diff --git a/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts b/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts index c962aa0274..84bcf1ff2c 100644 --- a/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts +++ b/packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts @@ -26,7 +26,7 @@ export const counterSlice = createSlice({ export function fetchCount(amount = 1) { return new Promise<{ data: number }>((resolve) => - setTimeout(() => resolve({ data: amount }), 500) + setTimeout(() => resolve({ data: amount }), 500), ) } @@ -36,7 +36,7 @@ export const incrementAsync = createAsyncThunk( const response = await fetchCount(amount) // The value we return becomes the `fulfilled` action payload return response.data - } + }, ) const { increment } = counterSlice.actions @@ -76,7 +76,7 @@ describe('startAppListening.withTypes', () => { expect(startAppListening.withTypes).toEqual(expect.any(Function)) expect(startAppListening.withTypes().withTypes).toEqual( - expect.any(Function) + expect.any(Function), ) expect(startAppListening).toBe(listenerMiddleware.startListening) @@ -108,7 +108,7 @@ describe('removeAppListener.withTypes', () => { expect(removeAppListener.withTypes).toEqual(expect.any(Function)) expect(removeAppListener.withTypes().withTypes).toEqual( - expect.any(Function) + expect.any(Function), ) expect(removeAppListener).toBe(removeListener) diff --git a/packages/toolkit/src/listenerMiddleware/tests/useCases.test.ts b/packages/toolkit/src/listenerMiddleware/tests/useCases.test.ts index 0bd4a13a7d..7517f9071d 100644 --- a/packages/toolkit/src/listenerMiddleware/tests/useCases.test.ts +++ b/packages/toolkit/src/listenerMiddleware/tests/useCases.test.ts @@ -87,7 +87,7 @@ describe('Saga-style Effects Scenarios', () => { ;(this.events[event] = this.events[event] || []).push(cb) return () => (this.events[event] = (this.events[event] || []).filter( - (l: any) => l !== cb + (l: any) => l !== cb, )) }, }) diff --git a/packages/toolkit/src/listenerMiddleware/types.ts b/packages/toolkit/src/listenerMiddleware/types.ts index fc6a304224..73a7ef1c0e 100644 --- a/packages/toolkit/src/listenerMiddleware/types.ts +++ b/packages/toolkit/src/listenerMiddleware/types.ts @@ -30,14 +30,14 @@ export interface TypedActionCreator { export type AnyListenerPredicate = ( action: UnknownAction, currentState: State, - originalState: State + originalState: State, ) => boolean /** @public */ export type ListenerPredicate = ( action: UnknownAction, currentState: State, - originalState: State + originalState: State, ) => action is Action /** @public */ @@ -144,7 +144,7 @@ export interface ForkOptions { export interface ListenerEffectAPI< State, Dispatch extends ReduxDispatch, - ExtraArgument = unknown + ExtraArgument = unknown, > extends MiddlewareAPI { /** * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran. @@ -272,10 +272,10 @@ export type ListenerEffect< Action extends ReduxAction, State, Dispatch extends ReduxDispatch, - ExtraArgument = unknown + ExtraArgument = unknown, > = ( action: Action, - api: ListenerEffectAPI + api: ListenerEffectAPI, ) => void | Promise /** @@ -316,7 +316,7 @@ export type ListenerMiddleware< unknown, UnknownAction >, - ExtraArgument = unknown + ExtraArgument = unknown, > = Middleware< { (action: ReduxAction<'listenerMiddleware/add'>): UnsubscribeListener @@ -333,7 +333,7 @@ export interface ListenerMiddlewareInstance< unknown, ReduxAction > = ThunkDispatch, - ExtraArgument = unknown + ExtraArgument = unknown, > { middleware: ListenerMiddleware @@ -361,31 +361,33 @@ export interface ListenerMiddlewareInstance< /** @public */ export type TakePatternOutputWithoutTimeout< State, - Predicate extends AnyListenerPredicate -> = Predicate extends MatchFunction - ? Promise<[Action, State, State]> - : Promise<[UnknownAction, State, State]> + Predicate extends AnyListenerPredicate, +> = + Predicate extends MatchFunction + ? Promise<[Action, State, State]> + : Promise<[UnknownAction, State, State]> /** @public */ export type TakePatternOutputWithTimeout< State, - Predicate extends AnyListenerPredicate -> = Predicate extends MatchFunction - ? Promise<[Action, State, State] | null> - : Promise<[UnknownAction, State, State] | null> + Predicate extends AnyListenerPredicate, +> = + Predicate extends MatchFunction + ? Promise<[Action, State, State] | null> + : Promise<[UnknownAction, State, State] | null> /** @public */ export interface TakePattern { >( - predicate: Predicate + predicate: Predicate, ): TakePatternOutputWithoutTimeout >( predicate: Predicate, - timeout: number + timeout: number, ): TakePatternOutputWithTimeout >( predicate: Predicate, - timeout?: number | undefined + timeout?: number | undefined, ): TakePatternOutputWithTimeout } @@ -396,7 +398,7 @@ export interface UnsubscribeListenerOptions { /** @public */ export type UnsubscribeListener = ( - unsubscribeOptions?: UnsubscribeListenerOptions + unsubscribeOptions?: UnsubscribeListenerOptions, ) => void /** @@ -412,7 +414,7 @@ export interface AddListenerOverloads< UnknownAction >, ExtraArgument = unknown, - AdditionalOptions = unknown + AdditionalOptions = unknown, > { /** Accepts a "listener predicate" that is also a TS type predicate for the action*/ < @@ -420,7 +422,7 @@ export interface AddListenerOverloads< ListenerPredicateType extends ListenerPredicate< MiddlewareActionType, StateType - > + >, >( options: { actionCreator?: never @@ -433,7 +435,7 @@ export interface AddListenerOverloads< DispatchType, ExtraArgument > - } & AdditionalOptions + } & AdditionalOptions, ): Return /** Accepts an RTK action creator, like `incrementByAmount` */ @@ -449,7 +451,7 @@ export interface AddListenerOverloads< DispatchType, ExtraArgument > - } & AdditionalOptions + } & AdditionalOptions, ): Return /** Accepts a specific action type string */ @@ -465,7 +467,7 @@ export interface AddListenerOverloads< DispatchType, ExtraArgument > - } & AdditionalOptions + } & AdditionalOptions, ): Return /** Accepts an RTK matcher function, such as `incrementByAmount.match` */ @@ -481,7 +483,7 @@ export interface AddListenerOverloads< DispatchType, ExtraArgument > - } & AdditionalOptions + } & AdditionalOptions, ): Return /** Accepts a "listener predicate" that just returns a boolean, no type assertion */ @@ -497,7 +499,7 @@ export interface AddListenerOverloads< DispatchType, ExtraArgument > - } & AdditionalOptions + } & AdditionalOptions, ): Return } @@ -508,7 +510,7 @@ export type RemoveListenerOverloads< StateType, unknown, UnknownAction - > + >, > = AddListenerOverloads< boolean, StateType, @@ -521,7 +523,7 @@ export type RemoveListenerOverloads< export interface RemoveListenerAction< Action extends UnknownAction, State, - Dispatch extends ReduxDispatch + Dispatch extends ReduxDispatch, > { type: 'listenerMiddleware/remove' payload: { @@ -544,7 +546,7 @@ export type TypedAddListener< >, ExtraArgument = unknown, Payload = ListenerEntry, - T extends string = 'listenerMiddleware/add' + T extends string = 'listenerMiddleware/add', > = BaseActionCreator & AddListenerOverloads< PayloadAction, @@ -579,7 +581,7 @@ export type TypedAddListener< OverrideStateType, unknown, UnknownAction - > + >, >() => TypedAddListener } @@ -596,7 +598,7 @@ export type TypedRemoveListener< UnknownAction >, Payload = ListenerEntry, - T extends string = 'listenerMiddleware/remove' + T extends string = 'listenerMiddleware/remove', > = BaseActionCreator & AddListenerOverloads< PayloadAction, @@ -632,7 +634,7 @@ export type TypedRemoveListener< OverrideStateType, unknown, UnknownAction - > + >, >() => TypedRemoveListener } @@ -648,7 +650,7 @@ export type TypedStartListening< unknown, UnknownAction >, - ExtraArgument = unknown + ExtraArgument = unknown, > = AddListenerOverloads< UnsubscribeListener, StateType, @@ -689,7 +691,7 @@ export type TypedStartListening< OverrideStateType, unknown, UnknownAction - > + >, >() => TypedStartListening } @@ -704,7 +706,7 @@ export type TypedStopListening< StateType, unknown, UnknownAction - > + >, > = RemoveListenerOverloads & { /** * Creates a "pre-typed" version of @@ -740,7 +742,7 @@ export type TypedStopListening< OverrideStateType, unknown, UnknownAction - > + >, >() => TypedStopListening } @@ -755,7 +757,7 @@ export type TypedCreateListenerEntry< StateType, unknown, UnknownAction - > + >, > = AddListenerOverloads< ListenerEntry, StateType, @@ -791,7 +793,7 @@ export type TypedCreateListenerEntry< OverrideStateType, unknown, UnknownAction - > + >, >() => TypedStopListening } @@ -802,7 +804,7 @@ export type TypedCreateListenerEntry< /** @internal An single listener entry */ export type ListenerEntry< State = unknown, - Dispatch extends ReduxDispatch = ReduxDispatch + Dispatch extends ReduxDispatch = ReduxDispatch, > = { id: string effect: ListenerEffect @@ -833,9 +835,5 @@ export type GuardedType = T extends (x: any, ...args: any[]) => x is infer T : never /** @public */ -export type ListenerPredicateGuardedActionType = T extends ListenerPredicate< - infer Action, - any -> - ? Action - : never +export type ListenerPredicateGuardedActionType = + T extends ListenerPredicate ? Action : never diff --git a/packages/toolkit/src/listenerMiddleware/utils.ts b/packages/toolkit/src/listenerMiddleware/utils.ts index f52e49b154..dd9480eb1f 100644 --- a/packages/toolkit/src/listenerMiddleware/utils.ts +++ b/packages/toolkit/src/listenerMiddleware/utils.ts @@ -2,10 +2,10 @@ import type { AbortSignalWithReason } from './types' export const assertFunction: ( func: unknown, - expected: string + expected: string, ) => asserts func is (...args: unknown[]) => unknown = ( func: unknown, - expected: string + expected: string, ) => { if (typeof func !== 'function') { throw new TypeError(`${expected} is not a function`) @@ -16,7 +16,7 @@ export const noop = () => {} export const catchRejection = ( promise: Promise, - onError = noop + onError = noop, ): Promise => { promise.catch(onError) @@ -25,7 +25,7 @@ export const catchRejection = ( export const addAbortSignalListener = ( abortSignal: AbortSignal, - callback: (evt: Event) => void + callback: (evt: Event) => void, ) => { abortSignal.addEventListener('abort', callback, { once: true }) return () => abortSignal.removeEventListener('abort', callback) @@ -43,7 +43,7 @@ export const addAbortSignalListener = ( */ export const abortControllerWithReason = ( abortController: AbortController, - reason: T + reason: T, ): void => { type Consumer = (val: T) => void diff --git a/packages/toolkit/src/mapBuilders.ts b/packages/toolkit/src/mapBuilders.ts index 5c6ac60010..560d640888 100644 --- a/packages/toolkit/src/mapBuilders.ts +++ b/packages/toolkit/src/mapBuilders.ts @@ -26,7 +26,7 @@ export interface ActionReducerMapBuilder { */ addCase>( actionCreator: ActionCreator, - reducer: CaseReducer> + reducer: CaseReducer>, ): ActionReducerMapBuilder /** * Adds a case reducer to handle a single exact action type. @@ -37,7 +37,7 @@ export interface ActionReducerMapBuilder { */ addCase>( type: Type, - reducer: CaseReducer + reducer: CaseReducer, ): ActionReducerMapBuilder /** @@ -98,7 +98,7 @@ const reducer = createReducer(initialState, (builder) => { */ addMatcher( matcher: TypeGuard | ((action: any) => boolean), - reducer: CaseReducer + reducer: CaseReducer, ): Omit, 'addCase'> /** @@ -124,11 +124,11 @@ const reducer = createReducer(initialState, builder => { } export function executeReducerBuilderCallback( - builderCallback: (builder: ActionReducerMapBuilder) => void + builderCallback: (builder: ActionReducerMapBuilder) => void, ): [ CaseReducers, ActionMatcherDescriptionCollection, - CaseReducer | undefined + CaseReducer | undefined, ] { const actionsMap: CaseReducers = {} const actionMatchers: ActionMatcherDescriptionCollection = [] @@ -136,7 +136,7 @@ export function executeReducerBuilderCallback( const builder = { addCase( typeOrActionCreator: string | TypedActionCreator, - reducer: CaseReducer + reducer: CaseReducer, ) { if (process.env.NODE_ENV !== 'production') { /* @@ -146,12 +146,12 @@ export function executeReducerBuilderCallback( */ if (actionMatchers.length > 0) { throw new Error( - '`builder.addCase` should only be called before calling `builder.addMatcher`' + '`builder.addCase` should only be called before calling `builder.addMatcher`', ) } if (defaultCaseReducer) { throw new Error( - '`builder.addCase` should only be called before calling `builder.addDefaultCase`' + '`builder.addCase` should only be called before calling `builder.addDefaultCase`', ) } } @@ -161,13 +161,13 @@ export function executeReducerBuilderCallback( : typeOrActionCreator.type if (!type) { throw new Error( - '`builder.addCase` cannot be called with an empty action type' + '`builder.addCase` cannot be called with an empty action type', ) } if (type in actionsMap) { throw new Error( '`builder.addCase` cannot be called with two reducers for the same action type ' + - `'${type}'` + `'${type}'`, ) } actionsMap[type] = reducer @@ -175,12 +175,12 @@ export function executeReducerBuilderCallback( }, addMatcher( matcher: TypeGuard, - reducer: CaseReducer + reducer: CaseReducer, ) { if (process.env.NODE_ENV !== 'production') { if (defaultCaseReducer) { throw new Error( - '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`' + '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`', ) } } diff --git a/packages/toolkit/src/matchers.ts b/packages/toolkit/src/matchers.ts index e8ca651077..6a5ccea09f 100644 --- a/packages/toolkit/src/matchers.ts +++ b/packages/toolkit/src/matchers.ts @@ -69,7 +69,7 @@ export function isAllOf[]]>( */ export function hasExpectedRequestMetadata( action: any, - validStatus: readonly string[] + validStatus: readonly string[], ) { if (!action || !action.meta) return false @@ -104,7 +104,7 @@ export type PendingActionFromAsyncThunk = * @public */ export function isPending(): ( - action: any + action: any, ) => action is UnknownAsyncThunkPendingAction /** * A higher-order function that returns a function that may be used to check @@ -116,7 +116,7 @@ export function isPending(): ( * @public */ export function isPending< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): (action: any) => action is PendingActionFromAsyncThunk @@ -126,7 +126,7 @@ export function isPending< */ export function isPending(action: any): action is UnknownAsyncThunkPendingAction export function isPending< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >(...asyncThunks: AsyncThunks | [any]) { if (asyncThunks.length === 0) { return (action: any) => hasExpectedRequestMetadata(action, ['pending']) @@ -137,11 +137,11 @@ export function isPending< } return ( - action: any + action: any, ): action is PendingActionFromAsyncThunk => { // note: this type will be correct because we have at least 1 asyncThunk const matchers: [Matcher, ...Matcher[]] = asyncThunks.map( - (asyncThunk) => asyncThunk.pending + (asyncThunk) => asyncThunk.pending, ) as any const combinedMatcher = isAnyOf(...matchers) @@ -165,7 +165,7 @@ export type RejectedActionFromAsyncThunk = * @public */ export function isRejected(): ( - action: any + action: any, ) => action is UnknownAsyncThunkRejectedAction /** * A higher-order function that returns a function that may be used to check @@ -177,7 +177,7 @@ export function isRejected(): ( * @public */ export function isRejected< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): (action: any) => action is RejectedActionFromAsyncThunk @@ -186,10 +186,10 @@ export function isRejected< * @public */ export function isRejected( - action: any + action: any, ): action is UnknownAsyncThunkRejectedAction export function isRejected< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >(...asyncThunks: AsyncThunks | [any]) { if (asyncThunks.length === 0) { return (action: any) => hasExpectedRequestMetadata(action, ['rejected']) @@ -200,11 +200,11 @@ export function isRejected< } return ( - action: any + action: any, ): action is RejectedActionFromAsyncThunk => { // note: this type will be correct because we have at least 1 asyncThunk const matchers: [Matcher, ...Matcher[]] = asyncThunks.map( - (asyncThunk) => asyncThunk.rejected + (asyncThunk) => asyncThunk.rejected, ) as any const combinedMatcher = isAnyOf(...matchers) @@ -231,7 +231,7 @@ export type RejectedWithValueActionFromAsyncThunk = * @public */ export function isRejectedWithValue(): ( - action: any + action: any, ) => action is UnknownAsyncThunkRejectedAction /** * A higher-order function that returns a function that may be used to check @@ -243,21 +243,21 @@ export function isRejectedWithValue(): ( * @public */ export function isRejectedWithValue< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): ( - action: any + action: any, ) => action is RejectedWithValueActionFromAsyncThunk /** * Tests if `action` is a rejected thunk action with value * @public */ export function isRejectedWithValue( - action: any + action: any, ): action is UnknownAsyncThunkRejectedAction export function isRejectedWithValue< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >(...asyncThunks: AsyncThunks | [any]) { const hasFlag = (action: any): action is any => { return action && action.meta && action.meta.rejectedWithValue @@ -276,7 +276,7 @@ export function isRejectedWithValue< } return ( - action: any + action: any, ): action is RejectedActionFromAsyncThunk => { const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag) @@ -299,7 +299,7 @@ export type FulfilledActionFromAsyncThunk = * @public */ export function isFulfilled(): ( - action: any + action: any, ) => action is UnknownAsyncThunkFulfilledAction /** * A higher-order function that returns a function that may be used to check @@ -311,7 +311,7 @@ export function isFulfilled(): ( * @public */ export function isFulfilled< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): (action: any) => action is FulfilledActionFromAsyncThunk @@ -320,10 +320,10 @@ export function isFulfilled< * @public */ export function isFulfilled( - action: any + action: any, ): action is UnknownAsyncThunkFulfilledAction export function isFulfilled< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >(...asyncThunks: AsyncThunks | [any]) { if (asyncThunks.length === 0) { return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled']) @@ -334,11 +334,11 @@ export function isFulfilled< } return ( - action: any + action: any, ): action is FulfilledActionFromAsyncThunk => { // note: this type will be correct because we have at least 1 asyncThunk const matchers: [Matcher, ...Matcher[]] = asyncThunks.map( - (asyncThunk) => asyncThunk.fulfilled + (asyncThunk) => asyncThunk.fulfilled, ) as any const combinedMatcher = isAnyOf(...matchers) @@ -370,7 +370,7 @@ export type ActionsFromAsyncThunk = * @public */ export function isAsyncThunkAction(): ( - action: any + action: any, ) => action is UnknownAsyncThunkAction /** * A higher-order function that returns a function that may be used to check @@ -381,7 +381,7 @@ export function isAsyncThunkAction(): ( * @public */ export function isAsyncThunkAction< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): (action: any) => action is ActionsFromAsyncThunk @@ -390,10 +390,10 @@ export function isAsyncThunkAction< * @public */ export function isAsyncThunkAction( - action: any + action: any, ): action is UnknownAsyncThunkAction export function isAsyncThunkAction< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >(...asyncThunks: AsyncThunks | [any]) { if (asyncThunks.length === 0) { return (action: any) => @@ -405,7 +405,7 @@ export function isAsyncThunkAction< } return ( - action: any + action: any, ): action is ActionsFromAsyncThunk => { // note: this type will be correct because we have at least 1 asyncThunk const matchers: [Matcher, ...Matcher[]] = [] as any @@ -414,7 +414,7 @@ export function isAsyncThunkAction< matchers.push( asyncThunk.pending, asyncThunk.rejected, - asyncThunk.fulfilled + asyncThunk.fulfilled, ) } diff --git a/packages/toolkit/src/query/HandledError.ts b/packages/toolkit/src/query/HandledError.ts index dcbf936b3b..c95791bd1d 100644 --- a/packages/toolkit/src/query/HandledError.ts +++ b/packages/toolkit/src/query/HandledError.ts @@ -1,6 +1,6 @@ export class HandledError { constructor( public readonly value: any, - public readonly meta: any = undefined + public readonly meta: any = undefined, ) {} } diff --git a/packages/toolkit/src/query/apiTypes.ts b/packages/toolkit/src/query/apiTypes.ts index 2aa7992999..e7d2332119 100644 --- a/packages/toolkit/src/query/apiTypes.ts +++ b/packages/toolkit/src/query/apiTypes.ts @@ -23,7 +23,7 @@ export interface ApiModules< // eslint-disable-next-line @typescript-eslint/no-unused-vars ReducerPath extends string, // eslint-disable-next-line @typescript-eslint/no-unused-vars - TagTypes extends string + TagTypes extends string, > {} export type ModuleName = keyof ApiModules @@ -34,7 +34,7 @@ export type Module = { BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, >( api: Api, options: WithRequiredProp< @@ -48,11 +48,11 @@ export type Module = { | 'invalidationBehavior' | 'tagTypes' >, - context: ApiContext + context: ApiContext, ): { injectEndpoint( endpointName: string, - definition: EndpointDefinition + definition: EndpointDefinition, ): void } } @@ -62,7 +62,7 @@ export interface ApiContext { endpointDefinitions: Definitions batch(cb: () => void): void extractRehydrationInfo: ( - action: UnknownAction + action: UnknownAction, ) => CombinedState | undefined hasRehydrationInfo: (action: UnknownAction) => boolean } @@ -72,7 +72,7 @@ export type Api< Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string, - Enhancers extends ModuleName = CoreModule + Enhancers extends ModuleName = CoreModule, > = UnionToIntersection< ApiModules[Enhancers] > & { @@ -81,7 +81,7 @@ export type Api< */ injectEndpoints(_: { endpoints: ( - build: EndpointBuilder + build: EndpointBuilder, ) => NewDefinitions overrideExisting?: boolean }): Api< @@ -96,7 +96,7 @@ export type Api< */ enhanceEndpoints< NewTagTypes extends string = never, - NewDefinitions extends EndpointDefinitions = never + NewDefinitions extends EndpointDefinitions = never, >(_: { addTagTypes?: readonly NewTagTypes[] endpoints?: UpdateDefinitions< diff --git a/packages/toolkit/src/query/baseQueryTypes.ts b/packages/toolkit/src/query/baseQueryTypes.ts index ed6a693c10..9af22a3f7e 100644 --- a/packages/toolkit/src/query/baseQueryTypes.ts +++ b/packages/toolkit/src/query/baseQueryTypes.ts @@ -37,20 +37,20 @@ export type BaseQueryFn< Result = unknown, Error = unknown, DefinitionExtraOptions = {}, - Meta = {} + Meta = {}, > = ( args: Args, api: BaseQueryApi, - extraOptions: DefinitionExtraOptions + extraOptions: DefinitionExtraOptions, ) => MaybePromise> export type BaseQueryEnhancer< AdditionalArgs = unknown, AdditionalDefinitionExtraOptions = unknown, - Config = void + Config = void, > = ( baseQuery: BaseQuery, - config: Config + config: Config, ) => BaseQueryFn< BaseQueryArg & AdditionalArgs, BaseQueryResult, @@ -59,13 +59,12 @@ export type BaseQueryEnhancer< NonNullable> > -export type BaseQueryResult = UnwrapPromise< - ReturnType -> extends infer Unwrapped - ? Unwrapped extends { data: any } - ? Unwrapped['data'] +export type BaseQueryResult = + UnwrapPromise> extends infer Unwrapped + ? Unwrapped extends { data: any } + ? Unwrapped['data'] + : never : never - : never export type BaseQueryMeta = UnwrapPromise< ReturnType diff --git a/packages/toolkit/src/query/core/apiState.ts b/packages/toolkit/src/query/core/apiState.ts index 71ca4856e4..cdf6831d2b 100644 --- a/packages/toolkit/src/query/core/apiState.ts +++ b/packages/toolkit/src/query/core/apiState.ts @@ -229,7 +229,7 @@ export type MutationSubState> = export type CombinedState< D extends EndpointDefinitions, E extends string, - ReducerPath extends string + ReducerPath extends string, > = { queries: QueryState mutations: MutationState @@ -272,7 +272,7 @@ export type MutationState = { export type RootState< Definitions extends EndpointDefinitions, TagTypes extends string, - ReducerPath extends string + ReducerPath extends string, > = { [P in ReducerPath]: CombinedState } diff --git a/packages/toolkit/src/query/core/buildInitiate.ts b/packages/toolkit/src/query/core/buildInitiate.ts index ae761f3855..384d10c50e 100644 --- a/packages/toolkit/src/query/core/buildInitiate.ts +++ b/packages/toolkit/src/query/core/buildInitiate.ts @@ -28,7 +28,7 @@ declare module './module' { export interface ApiEndpointQuery< Definition extends QueryDefinition, // eslint-disable-next-line @typescript-eslint/no-unused-vars - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, > { initiate: StartQueryActionCreator } @@ -36,7 +36,7 @@ declare module './module' { export interface ApiEndpointMutation< Definition extends MutationDefinition, // eslint-disable-next-line @typescript-eslint/no-unused-vars - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, > { initiate: StartMutationActionCreator } @@ -54,14 +54,14 @@ export interface StartQueryActionCreatorOptions { } type StartQueryActionCreator< - D extends QueryDefinition + D extends QueryDefinition, > = ( arg: QueryArgFrom, - options?: StartQueryActionCreatorOptions + options?: StartQueryActionCreatorOptions, ) => ThunkAction, any, any, UnknownAction> export type QueryActionCreatorResult< - D extends QueryDefinition + D extends QueryDefinition, > = SafePromise> & { arg: QueryArgFrom requestId: string @@ -75,7 +75,7 @@ export type QueryActionCreatorResult< } type StartMutationActionCreator< - D extends MutationDefinition + D extends MutationDefinition, > = ( arg: QueryArgFrom, options?: { @@ -87,11 +87,11 @@ type StartMutationActionCreator< */ track?: boolean fixedCacheKey?: string - } + }, ) => ThunkAction, any, any, UnknownAction> export type MutationActionCreatorResult< - D extends MutationDefinition + D extends MutationDefinition, > = SafePromise< | { data: ResultTypeFrom } | { @@ -246,7 +246,7 @@ export function buildInitiate({ * we could use it to validate the result, but it's probably not necessary */ _endpointName: string, - fixedCacheKeyOrRequestId: string + fixedCacheKeyOrRequestId: string, ) { return (dispatch: Dispatch) => { return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId] as @@ -269,7 +269,7 @@ export function buildInitiate({ if (process.env.NODE_ENV !== 'production') { if ((middlewareWarning as any).triggered) return const returnedValue = dispatch( - api.internalActions.internal_getRTKQSubscriptions() + api.internalActions.internal_getRTKQSubscriptions(), ) ;(middlewareWarning as any).triggered = true @@ -283,7 +283,7 @@ export function buildInitiate({ // Otherwise, must not have been added throw new Error( `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store. -You must add the middleware for RTK-Query to function correctly!` +You must add the middleware for RTK-Query to function correctly!`, ) } } @@ -291,7 +291,7 @@ You must add the middleware for RTK-Query to function correctly!` function buildInitiateQuery( endpointName: string, - endpointDefinition: QueryDefinition + endpointDefinition: QueryDefinition, ) { const queryAction: StartQueryActionCreator = ( @@ -301,7 +301,7 @@ You must add the middleware for RTK-Query to function correctly!` forceRefetch, subscriptionOptions, [forceQueryFnSymbol]: forceQueryFn, - } = {} + } = {}, ) => (dispatch, getState) => { const queryCacheKey = serializeQueryArgs({ @@ -342,14 +342,14 @@ You must add the middleware for RTK-Query to function correctly!` // -> we want to resolve it once data has been written with the data that will be written thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery - ? // a query has been skipped due to a condition and we do not have any currently running query - // -> we want to resolve it immediately with the current data - Promise.resolve(stateAfter) - : // query just started or one is already in flight - // -> wait for the running query, then resolve with data from after that - Promise.all([runningQuery, thunkResult]).then( - selectFromState - )) as SafePromise, + ? // a query has been skipped due to a condition and we do not have any currently running query + // -> we want to resolve it immediately with the current data + Promise.resolve(stateAfter) + : // query just started or one is already in flight + // -> wait for the running query, then resolve with data from after that + Promise.all([runningQuery, thunkResult]).then( + selectFromState, + )) as SafePromise, { arg, requestId, @@ -367,7 +367,7 @@ You must add the middleware for RTK-Query to function correctly!` }, refetch: () => dispatch( - queryAction(arg, { subscribe: false, forceRefetch: true }) + queryAction(arg, { subscribe: false, forceRefetch: true }), ), unsubscribe() { if (subscribe) @@ -375,7 +375,7 @@ You must add the middleware for RTK-Query to function correctly!` unsubscribeQueryResult({ queryCacheKey, requestId, - }) + }), ) }, updateSubscriptionOptions(options: SubscriptionOptions) { @@ -386,10 +386,10 @@ You must add the middleware for RTK-Query to function correctly!` requestId, queryCacheKey, options, - }) + }), ) }, - } + }, ) if (!runningQuery && !skippedSynchronously && !forceQueryFn) { @@ -411,7 +411,7 @@ You must add the middleware for RTK-Query to function correctly!` } function buildInitiateMutation( - endpointName: string + endpointName: string, ): StartMutationActionCreator { return (arg, { track = true, fixedCacheKey } = {}) => (dispatch, getState) => { @@ -427,7 +427,7 @@ You must add the middleware for RTK-Query to function correctly!` const { requestId, abort, unwrap } = thunkResult const returnValuePromise = asSafePromise( thunkResult.unwrap().then((data) => ({ data })), - (error) => ({ error }) + (error) => ({ error }), ) const reset = () => { diff --git a/packages/toolkit/src/query/core/buildMiddleware/batchActions.ts b/packages/toolkit/src/query/core/buildMiddleware/batchActions.ts index f941bcd544..b847dee01a 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/batchActions.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/batchActions.ts @@ -21,7 +21,7 @@ export const buildBatchedActionsHandler: InternalHandlerBuilder< // This is done to speed up perf when loading many components const actuallyMutateSubscriptions = ( mutableState: SubscriptionState, - action: Action + action: Action, ) => { if (updateSubscriptionOptions.match(action)) { const { queryCacheKey, requestId, options } = action.payload @@ -99,15 +99,15 @@ export const buildBatchedActionsHandler: InternalHandlerBuilder< return ( action, - mwApi + mwApi, ): [ actionShouldContinue: boolean, - result: SubscriptionSelectors | boolean + result: SubscriptionSelectors | boolean, ] => { if (!previousSubscriptions) { // Initialize it the first time this handler runs previousSubscriptions = JSON.parse( - JSON.stringify(internalState.currentSubscriptions) + JSON.stringify(internalState.currentSubscriptions), ) } @@ -128,7 +128,7 @@ export const buildBatchedActionsHandler: InternalHandlerBuilder< // Update subscription data based on this action const didMutate = actuallyMutateSubscriptions( internalState.currentSubscriptions, - action + action, ) let actionShouldContinue = true @@ -143,12 +143,12 @@ export const buildBatchedActionsHandler: InternalHandlerBuilder< updateSyncTimer = setTimeout(() => { // Deep clone the current subscription data const newSubscriptions: SubscriptionState = JSON.parse( - JSON.stringify(internalState.currentSubscriptions) + JSON.stringify(internalState.currentSubscriptions), ) // Figure out a smaller diff between original and current const [, patches] = produceWithPatches( previousSubscriptions, - () => newSubscriptions + () => newSubscriptions, ) // Sync the store state for visibility diff --git a/packages/toolkit/src/query/core/buildMiddleware/cacheCollection.ts b/packages/toolkit/src/query/core/buildMiddleware/cacheCollection.ts index becf6b8d1f..2d2ffeccf3 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/cacheCollection.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/cacheCollection.ts @@ -28,7 +28,7 @@ declare module '../../endpointDefinitions' { ResultType, QueryArg, BaseQuery extends BaseQueryFn, - ReducerPath extends string = string + ReducerPath extends string = string, > { /** * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_ @@ -64,7 +64,7 @@ export const buildCacheCollectionHandler: InternalHandlerBuilder = ({ const handler: ApiMiddlewareInternalHandler = ( action, mwApi, - internalState + internalState, ) => { if (unsubscribeQueryResult.match(action)) { const state = mwApi.getState()[reducerPath] @@ -74,7 +74,7 @@ export const buildCacheCollectionHandler: InternalHandlerBuilder = ({ queryCacheKey, state.queries[queryCacheKey]?.endpointName, mwApi, - state.config + state.config, ) } @@ -96,7 +96,7 @@ export const buildCacheCollectionHandler: InternalHandlerBuilder = ({ queryCacheKey as QueryCacheKey, queryState?.endpointName, mwApi, - state.config + state.config, ) } } @@ -106,7 +106,7 @@ export const buildCacheCollectionHandler: InternalHandlerBuilder = ({ queryCacheKey: QueryCacheKey, endpointName: string | undefined, api: SubMiddlewareApi, - config: ConfigState + config: ConfigState, ) { const endpointDefinition = context.endpointDefinitions[ endpointName! @@ -124,7 +124,7 @@ export const buildCacheCollectionHandler: InternalHandlerBuilder = ({ // Also avoid negative values too. const finalKeepUnusedDataFor = Math.max( 0, - Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS) + Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS), ) if (!anySubscriptionsRemainingForKey(queryCacheKey)) { diff --git a/packages/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts b/packages/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts index f4a8e9bd64..0a41e0174f 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts @@ -24,7 +24,7 @@ declare module '../../endpointDefinitions' { QueryArg, BaseQuery extends BaseQueryFn, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > extends LifecycleApi { /** * Gets the current value of this cache entry. @@ -47,7 +47,7 @@ declare module '../../endpointDefinitions' { QueryArg, BaseQuery extends BaseQueryFn, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > extends LifecycleApi { /** * Gets the current value of this cache entry. @@ -82,7 +82,7 @@ declare module '../../endpointDefinitions' { export interface CacheLifecyclePromises< ResultType = unknown, - MetaType = unknown + MetaType = unknown, > { /** * Promise that will resolve with the first value for this cache key. @@ -122,7 +122,7 @@ declare module '../../endpointDefinitions' { QueryArg, BaseQuery extends BaseQueryFn, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > extends QueryBaseLifecycleApi, CacheLifecyclePromises> {} @@ -130,7 +130,7 @@ declare module '../../endpointDefinitions' { QueryArg, BaseQuery extends BaseQueryFn, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > extends MutationBaseLifecycleApi< QueryArg, BaseQuery, @@ -144,11 +144,11 @@ declare module '../../endpointDefinitions' { ResultType, QueryArg, BaseQuery extends BaseQueryFn, - ReducerPath extends string = string + ReducerPath extends string = string, > { onCacheEntryAdded?( arg: QueryArg, - api: QueryCacheLifecycleApi + api: QueryCacheLifecycleApi, ): Promise | void } @@ -157,7 +157,7 @@ declare module '../../endpointDefinitions' { ResultType, QueryArg, BaseQuery extends BaseQueryFn, - ReducerPath extends string = string + ReducerPath extends string = string, > { onCacheEntryAdded?( arg: QueryArg, @@ -166,13 +166,13 @@ declare module '../../endpointDefinitions' { BaseQuery, ResultType, ReducerPath - > + >, ): Promise | void } } const neverResolvedError = new Error( - 'Promise never resolved before cacheEntryRemoved.' + 'Promise never resolved before cacheEntryRemoved.', ) as Error & { message: 'Promise never resolved before cacheEntryRemoved.' } @@ -198,7 +198,7 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({ const handler: ApiMiddlewareInternalHandler = ( action, mwApi, - stateBefore + stateBefore, ) => { const cacheKey = getCacheKey(action) @@ -211,7 +211,7 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({ action.meta.arg.originalArgs, cacheKey, mwApi, - action.meta.requestId + action.meta.requestId, ) } } else if (mutationThunk.pending.match(action)) { @@ -222,7 +222,7 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({ action.meta.arg.originalArgs, cacheKey, mwApi, - action.meta.requestId + action.meta.requestId, ) } } else if (isFulfilledThunk(action)) { @@ -268,7 +268,7 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({ originalArgs: any, queryCacheKey: string, mwApi: SubMiddlewareApi, - requestId: string + requestId: string, ) { const endpointDefinition = context.endpointDefinitions[endpointName] const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded @@ -297,7 +297,7 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({ const selector = (api.endpoints[endpointName] as any).select( endpointDefinition.type === DefinitionType.query ? originalArgs - : queryCacheKey + : queryCacheKey, ) const extra = mwApi.dispatch((_, __, extra) => extra) @@ -312,8 +312,8 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({ api.util.updateQueryData( endpointName as never, originalArgs, - updateRecipe - ) + updateRecipe, + ), ) : undefined) as any, diff --git a/packages/toolkit/src/query/core/buildMiddleware/index.ts b/packages/toolkit/src/query/core/buildMiddleware/index.ts index eecd189e84..4c44107368 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/index.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/index.ts @@ -29,7 +29,7 @@ import { buildBatchedActionsHandler } from './batchActions' export function buildMiddleware< Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, >(input: BuildMiddlewareInput) { const { reducerPath, queryThunk, api, context } = input const { apiUid } = context @@ -136,7 +136,7 @@ export function buildMiddleware< { status: QueryStatus.uninitialized } >, queryCacheKey: string, - override: Partial = {} + override: Partial = {}, ) { return queryThunk({ type: 'query', diff --git a/packages/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts b/packages/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts index 4334d4f813..150406a863 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts @@ -35,12 +35,12 @@ export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({ const { removeQueryResult } = api.internalActions const isThunkActionWithTags = isAnyOf( isFulfilled(mutationThunk), - isRejectedWithValue(mutationThunk) + isRejectedWithValue(mutationThunk), ) const isQueryEnd = isAnyOf( isFulfilled(mutationThunk, queryThunk), - isRejected(mutationThunk, queryThunk) + isRejected(mutationThunk, queryThunk), ) let pendingTagInvalidations: FullTagDescription[] = [] @@ -52,9 +52,9 @@ export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({ action, 'invalidatesTags', endpointDefinitions, - assertTagType + assertTagType, ), - mwApi + mwApi, ) } else if (isQueryEnd(action)) { invalidateTags([], mwApi) @@ -66,33 +66,38 @@ export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({ undefined, undefined, undefined, - assertTagType + assertTagType, ), - mwApi + mwApi, ) } } - function hasPendingRequests(state: CombinedState) { + function hasPendingRequests( + state: CombinedState, + ) { for (const key in state.queries) { - if (state.queries[key]?.status === QueryStatus.pending) return true; + if (state.queries[key]?.status === QueryStatus.pending) return true } for (const key in state.mutations) { - if (state.mutations[key]?.status === QueryStatus.pending) return true; + if (state.mutations[key]?.status === QueryStatus.pending) return true } - return false; + return false } function invalidateTags( newTags: readonly FullTagDescription[], - mwApi: SubMiddlewareApi + mwApi: SubMiddlewareApi, ) { const rootState = mwApi.getState() const state = rootState[reducerPath] pendingTagInvalidations.push(...newTags) - if (state.config.invalidationBehavior === 'delayed' && hasPendingRequests(state)) { + if ( + state.config.invalidationBehavior === 'delayed' && + hasPendingRequests(state) + ) { return } @@ -114,7 +119,7 @@ export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({ mwApi.dispatch( removeQueryResult({ queryCacheKey: queryCacheKey as QueryCacheKey, - }) + }), ) } else if (querySubState.status !== QueryStatus.uninitialized) { mwApi.dispatch(refetchQuery(querySubState, queryCacheKey)) diff --git a/packages/toolkit/src/query/core/buildMiddleware/polling.ts b/packages/toolkit/src/query/core/buildMiddleware/polling.ts index 2870d43443..6bee83fae4 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/polling.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/polling.ts @@ -51,7 +51,7 @@ export const buildPollingHandler: InternalHandlerBuilder = ({ function startNextPoll( { queryCacheKey }: QuerySubstateIdentifier, - api: SubMiddlewareApi + api: SubMiddlewareApi, ) { const state = api.getState()[reducerPath] const querySubState = state.queries[queryCacheKey] @@ -87,7 +87,7 @@ export const buildPollingHandler: InternalHandlerBuilder = ({ function updatePollingInterval( { queryCacheKey }: QuerySubstateIdentifier, - api: SubMiddlewareApi + api: SubMiddlewareApi, ) { const state = api.getState()[reducerPath] const querySubState = state.queries[queryCacheKey] @@ -133,7 +133,7 @@ export const buildPollingHandler: InternalHandlerBuilder = ({ if (!!subscribers[key].pollingInterval) { lowestPollingInterval = Math.min( subscribers[key].pollingInterval!, - lowestPollingInterval + lowestPollingInterval, ) skipPollingIfUnfocused = subscribers[key].skipPollingIfUnfocused || skipPollingIfUnfocused diff --git a/packages/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts b/packages/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts index 580581238c..ebb47b771c 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts @@ -19,7 +19,7 @@ export type ReferenceQueryLifecycle = never declare module '../../endpointDefinitions' { export interface QueryLifecyclePromises< ResultType, - BaseQuery extends BaseQueryFn + BaseQuery extends BaseQueryFn, > { /** * Promise that will resolve with the (transformed) query result. @@ -72,7 +72,7 @@ declare module '../../endpointDefinitions' { ResultType, QueryArg, BaseQuery extends BaseQueryFn, - ReducerPath extends string = string + ReducerPath extends string = string, > { /** * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call). @@ -114,7 +114,7 @@ declare module '../../endpointDefinitions' { */ onQueryStarted?( arg: QueryArg, - api: QueryLifecycleApi + api: QueryLifecycleApi, ): Promise | void } @@ -123,7 +123,7 @@ declare module '../../endpointDefinitions' { ResultType, QueryArg, BaseQuery extends BaseQueryFn, - ReducerPath extends string = string + ReducerPath extends string = string, > { /** * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call). @@ -175,7 +175,7 @@ declare module '../../endpointDefinitions' { */ onQueryStarted?( arg: QueryArg, - api: MutationLifecycleApi + api: MutationLifecycleApi, ): Promise | void } @@ -183,7 +183,7 @@ declare module '../../endpointDefinitions' { QueryArg, BaseQuery extends BaseQueryFn, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > extends QueryBaseLifecycleApi, QueryLifecyclePromises {} @@ -191,7 +191,7 @@ declare module '../../endpointDefinitions' { QueryArg, BaseQuery extends BaseQueryFn, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > extends MutationBaseLifecycleApi< QueryArg, BaseQuery, @@ -242,7 +242,7 @@ export const buildQueryLifecycleHandler: InternalHandlerBuilder = ({ const selector = (api.endpoints[endpointName] as any).select( endpointDefinition.type === DefinitionType.query ? originalArgs - : requestId + : requestId, ) const extra = mwApi.dispatch((_, __, extra) => extra) @@ -257,8 +257,8 @@ export const buildQueryLifecycleHandler: InternalHandlerBuilder = ({ api.util.updateQueryData( endpointName as never, originalArgs, - updateRecipe - ) + updateRecipe, + ), ) : undefined) as any, queryFulfilled, diff --git a/packages/toolkit/src/query/core/buildMiddleware/types.ts b/packages/toolkit/src/query/core/buildMiddleware/types.ts index 2e41e095f7..e2ab377b6c 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/types.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/types.ts @@ -41,7 +41,7 @@ export interface SubscriptionSelectors { export interface BuildMiddlewareInput< Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, > { reducerPath: ReducerPath context: ApiContext @@ -65,13 +65,13 @@ export interface BuildSubMiddlewareInput { status: QueryStatus.uninitialized } >, queryCacheKey: string, - override?: Partial + override?: Partial, ): AsyncThunkAction isThisApiSliceAction: (action: Action) => boolean } export type SubMiddlewareBuilder = ( - input: BuildSubMiddlewareInput + input: BuildSubMiddlewareInput, ) => Middleware< {}, RootState, @@ -83,11 +83,11 @@ type MwNext = Parameters>[0] export type ApiMiddlewareInternalHandler = ( action: Action, mwApi: SubMiddlewareApi & { next: MwNext }, - prevState: RootState + prevState: RootState, ) => Return export type InternalHandlerBuilder = ( - input: BuildSubMiddlewareInput + input: BuildSubMiddlewareInput, ) => ApiMiddlewareInternalHandler export interface PromiseConstructorWithKnownReason { @@ -100,8 +100,8 @@ export interface PromiseConstructorWithKnownReason { new ( executor: ( resolve: (value: T | PromiseLike) => void, - reject: (reason?: R) => void - ) => void + reject: (reason?: R) => void, + ) => void, ): PromiseWithKnownReason } @@ -121,7 +121,7 @@ export interface PromiseWithKnownReason onrejected?: | ((reason: R) => TResult2 | PromiseLike) | undefined - | null + | null, ): Promise /** @@ -133,6 +133,6 @@ export interface PromiseWithKnownReason onrejected?: | ((reason: R) => TResult | PromiseLike) | undefined - | null + | null, ): Promise } diff --git a/packages/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts b/packages/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts index 409bc56e08..d59df2eaa5 100644 --- a/packages/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts +++ b/packages/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts @@ -28,7 +28,7 @@ export const buildWindowEventHandler: InternalHandlerBuilder = ({ function refetchValidQueries( api: SubMiddlewareApi, - type: 'refetchOnFocus' | 'refetchOnReconnect' + type: 'refetchOnFocus' | 'refetchOnReconnect', ) { const state = api.getState()[reducerPath] const queries = state.queries @@ -43,10 +43,10 @@ export const buildWindowEventHandler: InternalHandlerBuilder = ({ const shouldRefetch = Object.values(subscriptionSubState).some( - (sub) => sub[type] === true + (sub) => sub[type] === true, ) || (Object.values(subscriptionSubState).every( - (sub) => sub[type] === undefined + (sub) => sub[type] === undefined, ) && state.config[type]) @@ -55,7 +55,7 @@ export const buildWindowEventHandler: InternalHandlerBuilder = ({ api.dispatch( removeQueryResult({ queryCacheKey: queryCacheKey as QueryCacheKey, - }) + }), ) } else if (querySubState.status !== QueryStatus.uninitialized) { api.dispatch(refetchQuery(querySubState, queryCacheKey)) diff --git a/packages/toolkit/src/query/core/buildSelectors.ts b/packages/toolkit/src/query/core/buildSelectors.ts index 8e151f809b..4ca49fc3e4 100644 --- a/packages/toolkit/src/query/core/buildSelectors.ts +++ b/packages/toolkit/src/query/core/buildSelectors.ts @@ -52,7 +52,7 @@ export const skipToken = /* @__PURE__ */ Symbol.for('RTKQ/skipToken') declare module './module' { export interface ApiEndpointQuery< Definition extends QueryDefinition, - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, > { select: QueryResultSelectorFactory< Definition, @@ -66,7 +66,7 @@ declare module './module' { export interface ApiEndpointMutation< Definition extends MutationDefinition, - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, > { select: MutationResultSelectorFactory< Definition, @@ -81,27 +81,27 @@ declare module './module' { type QueryResultSelectorFactory< Definition extends QueryDefinition, - RootState + RootState, > = ( - queryArg: QueryArgFrom | SkipToken + queryArg: QueryArgFrom | SkipToken, ) => (state: RootState) => QueryResultSelectorResult export type QueryResultSelectorResult< - Definition extends QueryDefinition + Definition extends QueryDefinition, > = QuerySubState & RequestStatusFlags type MutationResultSelectorFactory< Definition extends MutationDefinition, - RootState + RootState, > = ( requestId: | string | { requestId: string | undefined; fixedCacheKey: string | undefined } - | SkipToken + | SkipToken, ) => (state: RootState) => MutationResultSelectorResult export type MutationResultSelectorResult< - Definition extends MutationDefinition + Definition extends MutationDefinition, > = MutationSubState & RequestStatusFlags const initialSubState: QuerySubState = { @@ -111,16 +111,16 @@ const initialSubState: QuerySubState = { // abuse immer to freeze default states const defaultQuerySubState = /* @__PURE__ */ createNextState( initialSubState, - () => {} + () => {}, ) const defaultMutationSubState = /* @__PURE__ */ createNextState( initialSubState as MutationSubState, - () => {} + () => {}, ) export function buildSelectors< Definitions extends EndpointDefinitions, - ReducerPath extends string + ReducerPath extends string, >({ serializeQueryArgs, reducerPath, @@ -143,7 +143,7 @@ export function buildSelectors< } function withRequestFlags( - substate: T + substate: T, ): T & RequestStatusFlags { return { ...substate, @@ -158,7 +158,7 @@ export function buildSelectors< if ((selectInternalState as any).triggered) return state ;(selectInternalState as any).triggered = true console.error( - `Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?` + `Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`, ) } } @@ -167,7 +167,7 @@ export function buildSelectors< function buildQuerySelector( endpointName: string, - endpointDefinition: QueryDefinition + endpointDefinition: QueryDefinition, ) { return ((queryArgs: any) => { const serializedArgs = serializeQueryArgs({ @@ -207,7 +207,7 @@ export function buildSelectors< function selectInvalidatedBy( state: RootState, - tags: ReadonlyArray> + tags: ReadonlyArray>, ): Array<{ endpointName: string originalArgs: any @@ -245,24 +245,24 @@ export function buildSelectors< }, ] : [] - }) + }), ) } function selectCachedArgsForQuery>( state: RootState, - queryName: QueryName + queryName: QueryName, ): Array> { return Object.values(state[reducerPath].queries as QueryState) .filter( ( - entry + entry, ): entry is Exclude< QuerySubState, { status: QueryStatus.uninitialized } > => entry?.endpointName === queryName && - entry.status !== QueryStatus.uninitialized + entry.status !== QueryStatus.uninitialized, ) .map((entry) => entry.originalArgs) } diff --git a/packages/toolkit/src/query/core/buildSlice.ts b/packages/toolkit/src/query/core/buildSlice.ts index bb712281a9..f609e3a989 100644 --- a/packages/toolkit/src/query/core/buildSlice.ts +++ b/packages/toolkit/src/query/core/buildSlice.ts @@ -46,7 +46,7 @@ import { isUpsertQuery } from './buildInitiate' function updateQuerySubstateIfExists( state: QueryState, queryCacheKey: QueryCacheKey, - update: (substate: QuerySubState) => void + update: (substate: QuerySubState) => void, ) { const substate = state[queryCacheKey] if (substate) { @@ -57,7 +57,7 @@ function updateQuerySubstateIfExists( export function getMutationCacheKey( id: | MutationSubstateIdentifier - | { requestId: string; arg: { fixedCacheKey?: string | undefined } } + | { requestId: string; arg: { fixedCacheKey?: string | undefined } }, ): string export function getMutationCacheKey(id: { fixedCacheKey?: string @@ -68,7 +68,7 @@ export function getMutationCacheKey( id: | { fixedCacheKey?: string; requestId?: string } | MutationSubstateIdentifier - | { requestId: string; arg: { fixedCacheKey?: string | undefined } } + | { requestId: string; arg: { fixedCacheKey?: string | undefined } }, ): string | undefined { return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId } @@ -78,7 +78,7 @@ function updateMutationSubstateIfExists( id: | MutationSubstateIdentifier | { requestId: string; arg: { fixedCacheKey?: string | undefined } }, - update: (substate: MutationSubState) => void + update: (substate: MutationSubState) => void, ) { const substate = state[getMutationCacheKey(id)] if (substate) { @@ -119,7 +119,9 @@ export function buildSlice({ removeQueryResult: { reducer( draft, - { payload: { queryCacheKey } }: PayloadAction + { + payload: { queryCacheKey }, + }: PayloadAction, ) { delete draft[queryCacheKey] }, @@ -132,7 +134,7 @@ export function buildSlice({ payload: { queryCacheKey, patches }, }: PayloadAction< QuerySubstateIdentifier & { patches: readonly Patch[] } - > + >, ) { updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => { substate.data = applyPatches(substate.data as any, patches.concat()) @@ -200,7 +202,7 @@ export function buildSlice({ fulfilledTimeStamp, requestId, }) - } + }, ) substate.data = newData } else { @@ -215,14 +217,14 @@ export function buildSlice({ isDraft(substate.data) ? original(substate.data) : substate.data, - payload + payload, ) : payload } delete substate.error substate.fulfilledTimeStamp = meta.fulfilledTimeStamp - } + }, ) }) .addCase( @@ -240,9 +242,9 @@ export function buildSlice({ substate.status = QueryStatus.rejected substate.error = (payload ?? error) as any } - } + }, ) - } + }, ) .addMatcher(hasRehydrationInfo, (draft, action) => { const { queries } = extractRehydrationInfo(action)! @@ -285,7 +287,7 @@ export function buildSlice({ endpointName: arg.endpointName, startedTimeStamp, } - } + }, ) .addCase(mutationThunk.fulfilled, (draft, { payload, meta }) => { if (!meta.arg.track) return @@ -334,7 +336,7 @@ export function buildSlice({ action: PayloadAction<{ queryCacheKey: QueryCacheKey providedTags: readonly FullTagDescription[] - }> + }>, ) { const { queryCacheKey, providedTags } = action.payload @@ -370,7 +372,7 @@ export function buildSlice({ (draft, { payload: { queryCacheKey } }) => { for (const tagTypeSubscriptions of Object.values(draft)) { for (const idSubscriptions of Object.values( - tagTypeSubscriptions + tagTypeSubscriptions, )) { const foundAt = idSubscriptions.indexOf(queryCacheKey) if (foundAt !== -1) { @@ -378,7 +380,7 @@ export function buildSlice({ } } } - } + }, ) .addMatcher(hasRehydrationInfo, (draft, action) => { const { provided } = extractRehydrationInfo(action)! @@ -404,7 +406,7 @@ export function buildSlice({ action, 'providesTags', definitions, - assertTagType + assertTagType, ) const { queryCacheKey } = action.meta.arg @@ -413,9 +415,9 @@ export function buildSlice({ invalidationSlice.actions.updateProvidedBy({ queryCacheKey, providedTags, - }) + }), ) - } + }, ) }, }) @@ -433,13 +435,13 @@ export function buildSlice({ requestId: string options: Subscribers[number] } & QuerySubstateIdentifier - > + >, ) { // Dummy }, unsubscribeQueryResult( d, - a: PayloadAction<{ requestId: string } & QuerySubstateIdentifier> + a: PayloadAction<{ requestId: string } & QuerySubstateIdentifier>, ) { // Dummy }, diff --git a/packages/toolkit/src/query/core/buildThunks.ts b/packages/toolkit/src/query/core/buildThunks.ts index 70627228c4..2fe616bb7d 100644 --- a/packages/toolkit/src/query/core/buildThunks.ts +++ b/packages/toolkit/src/query/core/buildThunks.ts @@ -51,54 +51,55 @@ declare module './module' { export interface ApiEndpointQuery< Definition extends QueryDefinition, // eslint-disable-next-line @typescript-eslint/no-unused-vars - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, > extends Matchers {} export interface ApiEndpointMutation< Definition extends MutationDefinition, // eslint-disable-next-line @typescript-eslint/no-unused-vars - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, > extends Matchers {} } type EndpointThunk< Thunk extends QueryThunk | MutationThunk, - Definition extends EndpointDefinition -> = Definition extends EndpointDefinition< - infer QueryArg, - infer BaseQueryFn, - any, - infer ResultType -> - ? Thunk extends AsyncThunk - ? AsyncThunk< - ResultType, - ATArg & { originalArgs: QueryArg }, - ATConfig & { rejectValue: BaseQueryError } - > + Definition extends EndpointDefinition, +> = + Definition extends EndpointDefinition< + infer QueryArg, + infer BaseQueryFn, + any, + infer ResultType + > + ? Thunk extends AsyncThunk + ? AsyncThunk< + ResultType, + ATArg & { originalArgs: QueryArg }, + ATConfig & { rejectValue: BaseQueryError } + > + : never : never - : never export type PendingAction< Thunk extends QueryThunk | MutationThunk, - Definition extends EndpointDefinition + Definition extends EndpointDefinition, > = ReturnType['pending']> export type FulfilledAction< Thunk extends QueryThunk | MutationThunk, - Definition extends EndpointDefinition + Definition extends EndpointDefinition, > = ReturnType['fulfilled']> export type RejectedAction< Thunk extends QueryThunk | MutationThunk, - Definition extends EndpointDefinition + Definition extends EndpointDefinition, > = ReturnType['rejected']> export type Matcher = (value: any) => value is M export interface Matchers< Thunk extends QueryThunk | MutationThunk, - Definition extends EndpointDefinition + Definition extends EndpointDefinition, > { matchPending: Matcher> matchFulfilled: Matcher> @@ -156,36 +157,36 @@ function defaultTransformResponse(baseQueryReturnValue: unknown) { export type MaybeDrafted = T | Draft export type Recipe = (data: MaybeDrafted) => void | MaybeDrafted export type UpsertRecipe = ( - data: MaybeDrafted | undefined + data: MaybeDrafted | undefined, ) => void | MaybeDrafted export type PatchQueryDataThunk< Definitions extends EndpointDefinitions, - PartialState + PartialState, > = >( endpointName: EndpointName, args: QueryArgFrom, patches: readonly Patch[], - updateProvided?: boolean + updateProvided?: boolean, ) => ThunkAction export type UpdateQueryDataThunk< Definitions extends EndpointDefinitions, - PartialState + PartialState, > = >( endpointName: EndpointName, args: QueryArgFrom, updateRecipe: Recipe>, - updateProvided?: boolean + updateProvided?: boolean, ) => ThunkAction export type UpsertQueryDataThunk< Definitions extends EndpointDefinitions, - PartialState + PartialState, > = >( endpointName: EndpointName, args: QueryArgFrom, - value: ResultTypeFrom + value: ResultTypeFrom, ) => ThunkAction< QueryActionCreatorResult< Definitions[EndpointName] extends QueryDefinition @@ -218,7 +219,7 @@ export type PatchCollection = { export function buildThunks< BaseQuery extends BaseQueryFn, ReducerPath extends string, - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, >({ reducerPath, baseQuery, @@ -247,7 +248,7 @@ export function buildThunks< }) dispatch( - api.internalActions.queryResultPatched({ queryCacheKey, patches }) + api.internalActions.queryResultPatched({ queryCacheKey, patches }), ) if (!updateProvided) { @@ -256,7 +257,7 @@ export function buildThunks< const newValue = api.endpoints[endpointName].select(args)( // Work around TS 4.1 mismatch - getState() as RootState + getState() as RootState, ) const providedTags = calculateProvidedBy( @@ -265,11 +266,11 @@ export function buildThunks< undefined, args, {}, - assertTagType + assertTagType, ) dispatch( - api.internalActions.updateProvidedBy({ queryCacheKey, providedTags }) + api.internalActions.updateProvidedBy({ queryCacheKey, providedTags }), ) } @@ -280,7 +281,7 @@ export function buildThunks< const currentState = endpointDefinition.select(args)( // Work around TS 4.1 mismatch - getState() as RootState + getState() as RootState, ) let ret: PatchCollection = { @@ -292,8 +293,8 @@ export function buildThunks< endpointName, args, ret.inversePatches, - updateProvided - ) + updateProvided, + ), ), } if (currentState.status === QueryStatus.uninitialized) { @@ -304,7 +305,7 @@ export function buildThunks< if (isDraftable(currentState.data)) { const [value, patches, inversePatches] = produceWithPatches( currentState.data, - updateRecipe + updateRecipe, ) ret.patches.push(...patches) ret.inversePatches.push(...inversePatches) @@ -321,7 +322,12 @@ export function buildThunks< } dispatch( - api.util.patchQueryData(endpointName, args, ret.patches, updateProvided) + api.util.patchQueryData( + endpointName, + args, + ret.patches, + updateProvided, + ), ) return ret @@ -341,7 +347,7 @@ export function buildThunks< [forceQueryFnSymbol]: () => ({ data: value, }), - }) + }), ) } @@ -359,7 +365,7 @@ export function buildThunks< dispatch, getState, extra, - } + }, ) => { const endpointDefinition = endpointDefinitions[arg.endpointName] @@ -367,7 +373,7 @@ export function buildThunks< let transformResponse: ( baseQueryReturnValue: any, meta: any, - arg: any + arg: any, ) => any = defaultTransformResponse let result: QueryReturnValue const baseQueryApi = { @@ -390,7 +396,7 @@ export function buildThunks< result = await baseQuery( endpointDefinition.query(arg.originalArgs), baseQueryApi, - endpointDefinition.extraOptions as any + endpointDefinition.extraOptions as any, ) if (endpointDefinition.transformResponse) { @@ -402,7 +408,11 @@ export function buildThunks< baseQueryApi, endpointDefinition.extraOptions as any, (arg) => - baseQuery(arg, baseQueryApi, endpointDefinition.extraOptions as any) + baseQuery( + arg, + baseQueryApi, + endpointDefinition.extraOptions as any, + ), ) } if ( @@ -433,7 +443,7 @@ export function buildThunks< ${err} It needs to return an object with either the shape \`{ data: }\` or \`{ error: }\` that may contain an optional \`meta\` property. Object returned was:`, - result + result, ) } } @@ -446,7 +456,7 @@ export function buildThunks< fulfilledTimeStamp: Date.now(), baseQueryMeta: result.meta, [SHOULD_AUTOBATCH]: true, - } + }, ) } catch (error) { let catchedError = error @@ -454,7 +464,7 @@ export function buildThunks< let transformErrorResponse: ( baseQueryReturnValue: any, meta: any, - arg: any + arg: any, ) => any = defaultTransformResponse if ( @@ -468,9 +478,9 @@ export function buildThunks< await transformErrorResponse( catchedError.value, catchedError.meta, - arg.originalArgs + arg.originalArgs, ), - { baseQueryMeta: catchedError.meta, [SHOULD_AUTOBATCH]: true } + { baseQueryMeta: catchedError.meta, [SHOULD_AUTOBATCH]: true }, ) } catch (e) { catchedError = e @@ -483,7 +493,7 @@ export function buildThunks< console.error( `An unhandled error occurred processing a request for the endpoint "${arg.endpointName}". In the case of an unhandled error, no tags will be "provided" or "invalidated".`, - catchedError + catchedError, ) } else { console.error(catchedError) @@ -494,7 +504,7 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".` function isForcedQuery( arg: QueryThunkArg, - state: RootState + state: RootState, ) { const requestState = state[reducerPath]?.queries?.[arg.queryCacheKey] const baseFetchOnMountOrArgChange = @@ -586,14 +596,14 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".` const hasTheForce = (options: any): options is { force: boolean } => 'force' in options const hasMaxAge = ( - options: any + options: any, ): options is { ifOlderThan: false | number } => 'ifOlderThan' in options const prefetch = >( endpointName: EndpointName, arg: any, - options: PrefetchOptions + options: PrefetchOptions, ): ThunkAction => (dispatch: ThunkDispatch, getState: () => any) => { const force = hasTheForce(options) && options.force @@ -602,7 +612,7 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".` const queryAction = (force: boolean = true) => (api.endpoints[endpointName] as ApiEndpointQuery).initiate( arg, - { forceRefetch: force } + { forceRefetch: force }, ) const latestStateValue = ( api.endpoints[endpointName] as ApiEndpointQuery @@ -636,13 +646,13 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".` function buildMatchThunkActions< Thunk extends | AsyncThunk - | AsyncThunk + | AsyncThunk, >(thunk: Thunk, endpointName: string) { return { matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)), matchFulfilled: isAllOf( isFulfilled(thunk), - matchesEndpoint(endpointName) + matchesEndpoint(endpointName), ), matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName)), } as Matchers @@ -665,7 +675,7 @@ export function calculateProvidedByThunk( >, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, - assertTagType: AssertTagTypes + assertTagType: AssertTagTypes, ) { return calculateProvidedBy( endpointDefinitions[action.meta.arg.endpointName][type], @@ -673,6 +683,6 @@ export function calculateProvidedByThunk( isRejectedWithValue(action) ? action.payload : undefined, action.meta.arg.originalArgs, 'baseQueryMeta' in action.meta ? action.meta.baseQueryMeta : undefined, - assertTagType + assertTagType, ) } diff --git a/packages/toolkit/src/query/core/module.ts b/packages/toolkit/src/query/core/module.ts index 8d8ab6b117..c237c7b298 100644 --- a/packages/toolkit/src/query/core/module.ts +++ b/packages/toolkit/src/query/core/module.ts @@ -81,7 +81,7 @@ declare module '../apiTypes' { BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, - TagTypes extends string + TagTypes extends string, > { [coreModuleName]: { /** @@ -153,7 +153,7 @@ declare module '../apiTypes' { */ getRunningQueryThunk>( endpointName: EndpointName, - args: QueryArgFrom + args: QueryArgFrom, ): ThunkWithReturnValue< | QueryActionCreatorResult< Definitions[EndpointName] & { type: 'query' } @@ -173,7 +173,7 @@ declare module '../apiTypes' { */ getRunningMutationThunk>( endpointName: EndpointName, - fixedCacheKeyOrRequestId: string + fixedCacheKeyOrRequestId: string, ): ThunkWithReturnValue< | MutationActionCreatorResult< Definitions[EndpointName] & { type: 'mutation' } @@ -221,7 +221,7 @@ declare module '../apiTypes' { prefetch>( endpointName: EndpointName, arg: QueryArgFrom, - options: PrefetchOptions + options: PrefetchOptions, ): ThunkAction /** * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes. @@ -351,7 +351,7 @@ declare module '../apiTypes' { */ selectInvalidatedBy: ( state: RootState, - tags: ReadonlyArray> + tags: ReadonlyArray>, ) => Array<{ endpointName: string originalArgs: any @@ -365,7 +365,7 @@ declare module '../apiTypes' { */ selectCachedArgsForQuery: >( state: RootState, - queryName: QueryName + queryName: QueryName, ) => Array> } /** @@ -381,8 +381,8 @@ declare module '../apiTypes' { > ? ApiEndpointQuery : Definitions[K] extends MutationDefinition - ? ApiEndpointMutation - : never + ? ApiEndpointMutation + : never } } } @@ -392,7 +392,7 @@ export interface ApiEndpointQuery< // eslint-disable-next-line @typescript-eslint/no-unused-vars Definition extends QueryDefinition, // eslint-disable-next-line @typescript-eslint/no-unused-vars - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, > { name: string /** @@ -406,7 +406,7 @@ export interface ApiEndpointMutation< // eslint-disable-next-line @typescript-eslint/no-unused-vars Definition extends MutationDefinition, // eslint-disable-next-line @typescript-eslint/no-unused-vars - Definitions extends EndpointDefinitions + Definitions extends EndpointDefinitions, > { name: string /** @@ -464,7 +464,7 @@ export const coreModule = ({ refetchOnReconnect, invalidationBehavior, }, - context + context, ) { enablePatches() @@ -477,7 +477,7 @@ export const coreModule = ({ ) { if (!tagTypes.includes(tag.type as any)) { console.error( - `Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!` + `Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`, ) } } @@ -604,7 +604,7 @@ export const coreModule = ({ select: buildQuerySelector(endpointName, definition), initiate: buildInitiateQuery(endpointName, definition), }, - buildMatchThunkActions(queryThunk, endpointName) + buildMatchThunkActions(queryThunk, endpointName), ) } else if (isMutationDefinition(definition)) { safeAssign( @@ -614,7 +614,7 @@ export const coreModule = ({ select: buildMutationSelector(), initiate: buildInitiateMutation(endpointName), }, - buildMatchThunkActions(mutationThunk, endpointName) + buildMatchThunkActions(mutationThunk, endpointName), ) } }, diff --git a/packages/toolkit/src/query/core/setupListeners.ts b/packages/toolkit/src/query/core/setupListeners.ts index 01df593906..1c52042738 100644 --- a/packages/toolkit/src/query/core/setupListeners.ts +++ b/packages/toolkit/src/query/core/setupListeners.ts @@ -36,8 +36,8 @@ export function setupListeners( onFocusLost: typeof onFocusLost onOnline: typeof onOnline onOffline: typeof onOffline - } - ) => () => void + }, + ) => () => void, ) { function defaultHandler() { const handleFocus = () => dispatch(onFocus()) @@ -58,7 +58,7 @@ export function setupListeners( window.addEventListener( 'visibilitychange', handleVisibilityChange, - false + false, ) window.addEventListener('focus', handleFocus, false) diff --git a/packages/toolkit/src/query/createApi.ts b/packages/toolkit/src/query/createApi.ts index ed22f4ec9e..2a9eb4e9a2 100644 --- a/packages/toolkit/src/query/createApi.ts +++ b/packages/toolkit/src/query/createApi.ts @@ -17,7 +17,7 @@ export interface CreateApiOptions< BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', - TagTypes extends string = never + TagTypes extends string = never, > { /** * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements. @@ -97,7 +97,7 @@ export interface CreateApiOptions< * Endpoints are just a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are two basic endpoint types: [`query`](../../rtk-query/usage/queries) and [`mutation`](../../rtk-query/usage/mutations). */ endpoints( - build: EndpointBuilder + build: EndpointBuilder, ): Definitions /** * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache. @@ -200,7 +200,7 @@ export interface CreateApiOptions< reducerPath, }: { reducerPath: ReducerPath - } + }, ) => | undefined | CombinedState< @@ -220,9 +220,9 @@ export type CreateApi = { BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', - TagTypes extends string = never + TagTypes extends string = never, >( - options: CreateApiOptions + options: CreateApiOptions, ): Api } @@ -256,7 +256,7 @@ export function buildCreateApi, ...Module[]]>( const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) => options.extractRehydrationInfo?.(action, { reducerPath: (options.reducerPath ?? 'api') as any, - }) + }), ) const optionsWithDefaults: CreateApiOptions = { @@ -305,7 +305,7 @@ export function buildCreateApi, ...Module[]]>( apiUid: nanoid(), extractRehydrationInfo, hasRehydrationInfo: weakMapMemoize( - (action) => extractRehydrationInfo(action) != null + (action) => extractRehydrationInfo(action) != null, ), } @@ -321,14 +321,14 @@ export function buildCreateApi, ...Module[]]>( } if (endpoints) { for (const [endpointName, partialDefinition] of Object.entries( - endpoints + endpoints, )) { if (typeof partialDefinition === 'function') { partialDefinition(context.endpointDefinitions[endpointName]) } else { Object.assign( context.endpointDefinitions[endpointName] || {}, - partialDefinition + partialDefinition, ) } } @@ -338,19 +338,19 @@ export function buildCreateApi, ...Module[]]>( } as Api const initializedModules = modules.map((m) => - m.init(api as any, optionsWithDefaults as any, context) + m.init(api as any, optionsWithDefaults as any, context), ) function injectEndpoints( - inject: Parameters[0] + inject: Parameters[0], ) { const evaluatedEndpoints = inject.endpoints({ - query: (x) => ({ ...x, type: DefinitionType.query } as any), - mutation: (x) => ({ ...x, type: DefinitionType.mutation } as any), + query: (x) => ({ ...x, type: DefinitionType.query }) as any, + mutation: (x) => ({ ...x, type: DefinitionType.mutation }) as any, }) for (const [endpointName, definition] of Object.entries( - evaluatedEndpoints + evaluatedEndpoints, )) { if ( !inject.overrideExisting && @@ -361,7 +361,7 @@ export function buildCreateApi, ...Module[]]>( process.env.NODE_ENV === 'development' ) { console.error( - `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\`` + `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``, ) } diff --git a/packages/toolkit/src/query/defaultSerializeQueryArgs.ts b/packages/toolkit/src/query/defaultSerializeQueryArgs.ts index e3fe011b44..fcfd63aeb9 100644 --- a/packages/toolkit/src/query/defaultSerializeQueryArgs.ts +++ b/packages/toolkit/src/query/defaultSerializeQueryArgs.ts @@ -25,7 +25,7 @@ export const defaultSerializeQueryArgs: SerializeQueryArgs = ({ acc[key] = (value as any)[key] return acc }, {}) - : value + : value, ) if (isPlainObject(queryArgs)) { cache?.set(queryArgs, stringified) diff --git a/packages/toolkit/src/query/endpointDefinitions.ts b/packages/toolkit/src/query/endpointDefinitions.ts index 42f844cfe2..1a552fae94 100644 --- a/packages/toolkit/src/query/endpointDefinitions.ts +++ b/packages/toolkit/src/query/endpointDefinitions.ts @@ -27,7 +27,7 @@ const baseQuery = /* @__PURE__ */ Symbol() interface EndpointDefinitionWithQuery< QueryArg, BaseQuery extends BaseQueryFn, - ResultType + ResultType, > { /** * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking. @@ -75,7 +75,7 @@ interface EndpointDefinitionWithQuery< transformResponse?( baseQueryReturnValue: BaseQueryResult, meta: BaseQueryMeta, - arg: QueryArg + arg: QueryArg, ): ResultType | Promise /** * A function to manipulate the data returned by a failed query or mutation. @@ -83,7 +83,7 @@ interface EndpointDefinitionWithQuery< transformErrorResponse?( baseQueryReturnValue: BaseQueryError, meta: BaseQueryMeta, - arg: QueryArg + arg: QueryArg, ): unknown /** * Defaults to `true`. @@ -103,7 +103,7 @@ interface EndpointDefinitionWithQuery< interface EndpointDefinitionWithQueryFn< QueryArg, BaseQuery extends BaseQueryFn, - ResultType + ResultType, > { /** * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint. @@ -147,7 +147,7 @@ interface EndpointDefinitionWithQueryFn< arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions, - baseQuery: (arg: Parameters[0]) => ReturnType + baseQuery: (arg: Parameters[0]) => ReturnType, ): MaybePromise< QueryReturnValue< ResultType, @@ -176,7 +176,7 @@ interface EndpointDefinitionWithQueryFn< export interface BaseEndpointTypes< QueryArg, BaseQuery extends BaseQueryFn, - ResultType + ResultType, > { QueryArg: QueryArg BaseQuery: BaseQuery @@ -186,7 +186,7 @@ export interface BaseEndpointTypes< export type BaseEndpointDefinition< QueryArg, BaseQuery extends BaseQueryFn, - ResultType + ResultType, > = ( | ([CastAny, {}>] extends [NEVER] ? never @@ -213,12 +213,12 @@ export type GetResultDescriptionFn< ResultType, QueryArg, ErrorType, - MetaType + MetaType, > = ( result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, - meta: MetaType + meta: MetaType, ) => ReadonlyArray> export type FullTagDescription = { @@ -231,7 +231,7 @@ export type ResultDescription< ResultType, QueryArg, ErrorType, - MetaType + MetaType, > = | ReadonlyArray> | GetResultDescriptionFn @@ -241,7 +241,7 @@ export interface QueryTypes< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > extends BaseEndpointTypes { /** * The endpoint definition type. To be used with some internal generic types. @@ -266,7 +266,7 @@ export interface QueryExtraOptions< ResultType, QueryArg, BaseQuery extends BaseQueryFn, - ReducerPath extends string = string + ReducerPath extends string = string, > { type: DefinitionType.query /** @@ -445,7 +445,7 @@ export interface QueryExtraOptions< baseQueryMeta: BaseQueryMeta requestId: string fulfilledTimeStamp: number - } + }, ): ResultType | void /** @@ -506,7 +506,7 @@ export type QueryDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = BaseEndpointDefinition & QueryExtraOptions @@ -515,7 +515,7 @@ export interface MutationTypes< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > extends BaseEndpointTypes { /** * The endpoint definition type. To be used with some internal generic types. @@ -540,7 +540,7 @@ export interface MutationExtraOptions< ResultType, QueryArg, BaseQuery extends BaseQueryFn, - ReducerPath extends string = string + ReducerPath extends string = string, > { type: DefinitionType.mutation /** @@ -611,7 +611,7 @@ export type MutationDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = BaseEndpointDefinition & MutationExtraOptions @@ -620,7 +620,7 @@ export type EndpointDefinition< BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, - ReducerPath extends string = string + ReducerPath extends string = string, > = | QueryDefinition | MutationDefinition @@ -631,13 +631,13 @@ export type EndpointDefinitions = Record< > export function isQueryDefinition( - e: EndpointDefinition + e: EndpointDefinition, ): e is QueryDefinition { return e.type === DefinitionType.query } export function isMutationDefinition( - e: EndpointDefinition + e: EndpointDefinition, ): e is MutationDefinition { return e.type === DefinitionType.mutation } @@ -645,7 +645,7 @@ export function isMutationDefinition( export type EndpointBuilder< BaseQuery extends BaseQueryFn, TagTypes extends string, - ReducerPath extends string + ReducerPath extends string, > = { /** * An endpoint definition that retrieves data, and may provide tags to the cache. @@ -677,7 +677,7 @@ export type EndpointBuilder< definition: OmitFromUnion< QueryDefinition, 'type' - > + >, ): QueryDefinition /** * An endpoint definition that alters data on the server or will possibly invalidate the cache. @@ -715,7 +715,7 @@ export type EndpointBuilder< ReducerPath >, 'type' - > + >, ): MutationDefinition } @@ -729,14 +729,14 @@ export function calculateProvidedBy( error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, - assertTagTypes: AssertTagTypes + assertTagTypes: AssertTagTypes, ): readonly FullTagDescription[] { if (isFunction(description)) { return description( result as ResultType, error as undefined, queryArg, - meta as MetaType + meta as MetaType, ) .map(expandTagDescription) .map(assertTagTypes) @@ -752,7 +752,7 @@ function isFunction(t: T): t is Extract { } export function expandTagDescription( - description: TagDescription + description: TagDescription, ): FullTagDescription { return typeof description === 'string' ? { type: description } : description } @@ -763,29 +763,22 @@ export type ResultTypeFrom> = D extends BaseEndpointDefinition ? RT : unknown export type ReducerPathFrom< - D extends EndpointDefinition + D extends EndpointDefinition, > = D extends EndpointDefinition ? RP : unknown export type TagTypesFrom> = D extends EndpointDefinition ? RP : unknown -export type TagTypesFromApi = T extends Api - ? TagTypes - : never +export type TagTypesFromApi = + T extends Api ? TagTypes : never -export type DefinitionsFromApi = T extends Api< - any, - infer Definitions, - any, - any -> - ? Definitions - : never +export type DefinitionsFromApi = + T extends Api ? Definitions : never export type TransformedResponse< NewDefinitions extends EndpointDefinitions, K, - ResultType + ResultType, > = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType @@ -804,25 +797,25 @@ export type OverrideResultType = > ? QueryDefinition : Definition extends MutationDefinition< - infer QueryArg, - infer BaseQuery, - infer TagTypes, - any, - infer ReducerPath - > - ? MutationDefinition< - QueryArg, - BaseQuery, - TagTypes, - NewResultType, - ReducerPath - > - : never + infer QueryArg, + infer BaseQuery, + infer TagTypes, + any, + infer ReducerPath + > + ? MutationDefinition< + QueryArg, + BaseQuery, + TagTypes, + NewResultType, + ReducerPath + > + : never export type UpdateDefinitions< Definitions extends EndpointDefinitions, NewTagTypes extends string, - NewDefinitions extends EndpointDefinitions + NewDefinitions extends EndpointDefinitions, > = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition< infer QueryArg, @@ -839,18 +832,18 @@ export type UpdateDefinitions< ReducerPath > : Definitions[K] extends MutationDefinition< - infer QueryArg, - infer BaseQuery, - any, - infer ResultType, - infer ReducerPath - > - ? MutationDefinition< - QueryArg, - BaseQuery, - NewTagTypes, - TransformedResponse, - ReducerPath - > - : never + infer QueryArg, + infer BaseQuery, + any, + infer ResultType, + infer ReducerPath + > + ? MutationDefinition< + QueryArg, + BaseQuery, + NewTagTypes, + TransformedResponse, + ReducerPath + > + : never } diff --git a/packages/toolkit/src/query/fakeBaseQuery.ts b/packages/toolkit/src/query/fakeBaseQuery.ts index 54def42b33..4e1c4f2270 100644 --- a/packages/toolkit/src/query/fakeBaseQuery.ts +++ b/packages/toolkit/src/query/fakeBaseQuery.ts @@ -15,7 +15,7 @@ export function fakeBaseQuery(): BaseQueryFn< > { return function () { throw new Error( - 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.' + 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.', ) } } diff --git a/packages/toolkit/src/query/fetchBaseQuery.ts b/packages/toolkit/src/query/fetchBaseQuery.ts index 055bf6f47b..00cf6e54ab 100644 --- a/packages/toolkit/src/query/fetchBaseQuery.ts +++ b/packages/toolkit/src/query/fetchBaseQuery.ts @@ -112,11 +112,11 @@ export type FetchBaseQueryArgs = { api: Pick< BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced' - > + >, ) => MaybePromise fetchFn?: ( input: RequestInfo, - init?: RequestInit | undefined + init?: RequestInit | undefined, ) => Promise paramsSerializer?: (params: Record) => string /** @@ -209,7 +209,7 @@ export function fetchBaseQuery({ > { if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) { console.warn( - 'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.' + 'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.', ) } return async (arg, api) => { @@ -301,13 +301,13 @@ export function fetchBaseQuery({ await Promise.all([ handleResponse(response, responseHandler).then( (r) => (resultData = r), - (e) => (handleResponseError = e) + (e) => (handleResponseError = e), ), // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182 // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios responseClone.text().then( (r) => (responseText = r), - () => {} + () => {}, ), ]) if (handleResponseError) throw handleResponseError @@ -339,7 +339,7 @@ export function fetchBaseQuery({ async function handleResponse( response: Response, - responseHandler: ResponseHandler + responseHandler: ResponseHandler, ) { if (typeof responseHandler === 'function') { return responseHandler(response) diff --git a/packages/toolkit/src/query/react/ApiProvider.tsx b/packages/toolkit/src/query/react/ApiProvider.tsx index 4c9f7acf23..a2d56f3ae2 100644 --- a/packages/toolkit/src/query/react/ApiProvider.tsx +++ b/packages/toolkit/src/query/react/ApiProvider.tsx @@ -42,7 +42,7 @@ export function ApiProvider>(props: { const existingContext = useContext(context) if (existingContext) { throw new Error( - 'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.' + 'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.', ) } const [store] = React.useState(() => @@ -51,7 +51,7 @@ export function ApiProvider>(props: { [props.api.reducerPath]: props.api.reducer, }, middleware: (gDM) => gDM().concat(props.api.middleware), - }) + }), ) // Adds the event listeners for online/offline/focus/etc useEffect( @@ -59,7 +59,7 @@ export function ApiProvider>(props: { props.setupListeners === false ? undefined : setupListeners(store.dispatch, props.setupListeners), - [props.setupListeners, store.dispatch] + [props.setupListeners, store.dispatch], ) return ( diff --git a/packages/toolkit/src/query/react/buildHooks.ts b/packages/toolkit/src/query/react/buildHooks.ts index 5a524719cf..b6d611b778 100644 --- a/packages/toolkit/src/query/react/buildHooks.ts +++ b/packages/toolkit/src/query/react/buildHooks.ts @@ -61,7 +61,7 @@ export const useIsomorphicLayoutEffect = : useEffect export interface QueryHooks< - Definition extends QueryDefinition + Definition extends QueryDefinition, > { useQuery: UseQuery useLazyQuery: UseLazyQuery @@ -71,7 +71,7 @@ export interface QueryHooks< } export interface MutationHooks< - Definition extends MutationDefinition + Definition extends MutationDefinition, > { useMutation: UseMutation } @@ -92,15 +92,15 @@ export interface MutationHooks< * - Re-renders as the request status changes and data becomes available */ export type UseQuery> = < - R extends Record = UseQueryStateDefaultResult + R extends Record = UseQueryStateDefaultResult, >( arg: QueryArgFrom | SkipToken, - options?: UseQuerySubscriptionOptions & UseQueryStateOptions + options?: UseQuerySubscriptionOptions & UseQueryStateOptions, ) => UseQueryHookResult export type UseQueryHookResult< D extends QueryDefinition, - R = UseQueryStateDefaultResult + R = UseQueryStateDefaultResult, > = UseQueryStateResult & UseQuerySubscriptionResult /** @@ -113,7 +113,7 @@ export type TypedUseQueryHookResult< BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult< QueryDefinition - > + >, > = TypedUseQueryStateResult & TypedUseQuerySubscriptionResult @@ -176,14 +176,14 @@ interface UseQuerySubscriptionOptions extends SubscriptionOptions { * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met */ export type UseQuerySubscription< - D extends QueryDefinition + D extends QueryDefinition, > = ( arg: QueryArgFrom | SkipToken, - options?: UseQuerySubscriptionOptions + options?: UseQuerySubscriptionOptions, ) => UseQuerySubscriptionResult export type UseQuerySubscriptionResult< - D extends QueryDefinition + D extends QueryDefinition, > = Pick, 'refetch'> /** @@ -193,13 +193,13 @@ export type UseQuerySubscriptionResult< export type TypedUseQuerySubscriptionResult< ResultType, QueryArg, - BaseQuery extends BaseQueryFn + BaseQuery extends BaseQueryFn, > = UseQuerySubscriptionResult< QueryDefinition > export type UseLazyQueryLastPromiseInfo< - D extends QueryDefinition + D extends QueryDefinition, > = { lastArg: QueryArgFrom } @@ -222,13 +222,13 @@ export type UseLazyQueryLastPromiseInfo< * When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists. */ export type UseLazyQuery> = < - R extends Record = UseQueryStateDefaultResult + R extends Record = UseQueryStateDefaultResult, >( - options?: SubscriptionOptions & Omit, 'skip'> + options?: SubscriptionOptions & Omit, 'skip'>, ) => [ LazyQueryTrigger, UseQueryStateResult, - UseLazyQueryLastPromiseInfo + UseLazyQueryLastPromiseInfo, ] export type LazyQueryTrigger> = { @@ -254,7 +254,7 @@ export type LazyQueryTrigger> = { */ ( arg: QueryArgFrom, - preferCacheValue?: boolean + preferCacheValue?: boolean, ): QueryActionCreatorResult } @@ -270,14 +270,14 @@ export type LazyQueryTrigger> = { * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once */ export type UseLazyQuerySubscription< - D extends QueryDefinition + D extends QueryDefinition, > = ( - options?: SubscriptionOptions + options?: SubscriptionOptions, ) => readonly [LazyQueryTrigger, QueryArgFrom | UninitializedValue] export type QueryStateSelector< R extends Record, - D extends QueryDefinition + D extends QueryDefinition, > = (state: UseQueryStateDefaultResult) => R /** @@ -291,15 +291,15 @@ export type QueryStateSelector< * - Re-renders as the request status changes and data becomes available */ export type UseQueryState> = < - R extends Record = UseQueryStateDefaultResult + R extends Record = UseQueryStateDefaultResult, >( arg: QueryArgFrom | SkipToken, - options?: UseQueryStateOptions + options?: UseQueryStateOptions, ) => UseQueryStateResult export type UseQueryStateOptions< D extends QueryDefinition, - R extends Record + R extends Record, > = { /** * Prevents a query from automatically running. @@ -369,7 +369,7 @@ export type UseQueryStateOptions< export type UseQueryStateResult< _ extends QueryDefinition, - R + R, > = TSHelpersNoInfer /** @@ -382,7 +382,7 @@ export type TypedUseQueryStateResult< BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult< QueryDefinition - > + >, > = TSHelpersNoInfer type UseQueryStateBaseResult> = @@ -459,12 +459,12 @@ type UseQueryStateDefaultResult> = export type MutationStateSelector< R extends Record, - D extends MutationDefinition + D extends MutationDefinition, > = (state: MutationResultSelectorResult) => R export type UseMutationStateOptions< D extends MutationDefinition, - R extends Record + R extends Record, > = { selectFromResult?: MutationStateSelector fixedCacheKey?: string @@ -472,7 +472,7 @@ export type UseMutationStateOptions< export type UseMutationStateResult< D extends MutationDefinition, - R + R, > = TSHelpersNoInfer & { originalArgs?: QueryArgFrom /** @@ -492,7 +492,7 @@ export type TypedUseMutationResult< BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult< MutationDefinition - > + >, > = UseMutationStateResult< MutationDefinition, R @@ -509,9 +509,9 @@ export type TypedUseMutationResult< * - Re-renders as the request status changes and data becomes available */ export type UseMutation> = < - R extends Record = MutationResultSelectorResult + R extends Record = MutationResultSelectorResult, >( - options?: UseMutationStateOptions + options?: UseMutationStateOptions, ) => readonly [MutationTrigger, UseMutationStateResult] export type MutationTrigger> = @@ -542,7 +542,7 @@ export type MutationTrigger> = * to prevent that the library user has to do an additional check for `isUninitialized`/ */ const noPendingQueryStateSelector: QueryStateSelector = ( - selected + selected, ) => { if (selected.isUninitialized) { return { @@ -559,7 +559,7 @@ const noPendingQueryStateSelector: QueryStateSelector = ( type GenericPrefetchThunk = ( endpointName: any, arg: any, - options: PrefetchOptions + options: PrefetchOptions, ) => ThunkAction /** @@ -588,7 +588,7 @@ export function buildHooks({ }) { const usePossiblyImmediateEffect: ( effect: () => void | undefined, - deps?: DependencyList + deps?: DependencyList, ) => void = unstable__sideEffectsInRender ? (cb) => cb() : useEffect return { buildQueryHooks, buildMutationHook, usePrefetch } @@ -596,7 +596,7 @@ export function buildHooks({ function queryStatePreSelector( currentState: QueryResultSelectorResult, lastResult: UseQueryStateDefaultResult | undefined, - queryArgs: any + queryArgs: any, ): UseQueryStateDefaultResult { // if we had a last result and the current result is uninitialized, // we might have called `api.util.resetApiState` @@ -644,7 +644,7 @@ export function buildHooks({ function usePrefetch>( endpointName: EndpointName, - defaultOptions?: PrefetchOptions + defaultOptions?: PrefetchOptions, ) { const dispatch = useDispatch>() const stableDefaultOptions = useShallowStableValue(defaultOptions) @@ -655,9 +655,9 @@ export function buildHooks({ (api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, { ...stableDefaultOptions, ...options, - }) + }), ), - [endpointName, dispatch, stableDefaultOptions] + [endpointName, dispatch, stableDefaultOptions], ) } @@ -671,7 +671,7 @@ export function buildHooks({ skip = false, pollingInterval = 0, skipPollingIfUnfocused = false, - } = {} + } = {}, ) => { const { initiate } = api.endpoints[name] as ApiEndpointQuery< QueryDefinition, @@ -681,7 +681,7 @@ export function buildHooks({ const subscriptionSelectorsRef = useRef() if (!subscriptionSelectorsRef.current) { const returnedValue = dispatch( - api.internalActions.internal_getRTKQSubscriptions() + api.internalActions.internal_getRTKQSubscriptions(), ) if (process.env.NODE_ENV !== 'production') { @@ -691,7 +691,7 @@ export function buildHooks({ ) { throw new Error( `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store. - You must add the middleware for RTK-Query to function correctly!` + You must add the middleware for RTK-Query to function correctly!`, ) } } @@ -708,7 +708,7 @@ export function buildHooks({ // and then we never try to initiate a refetch. defaultSerializeQueryArgs, context.endpointDefinitions[name], - name + name, ) const stableSubscriptionOptions = useShallowStableValue({ refetchOnReconnect, @@ -730,7 +730,7 @@ export function buildHooks({ currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed( queryCacheKey, - requestId + requestId, ) } @@ -771,7 +771,7 @@ export function buildHooks({ initiate(stableArg, { subscriptionOptions: stableSubscriptionOptions, forceRefetch: refetchOnMountOrArgChange, - }) + }), ) promiseRef.current = promise @@ -802,12 +802,12 @@ export function buildHooks({ refetch: () => { if (!promiseRef.current) throw new Error( - 'Cannot refetch a query that has not been started yet.' + 'Cannot refetch a query that has not been started yet.', ) return promiseRef.current?.refetch() }, }), - [] + [], ) } @@ -838,7 +838,7 @@ export function buildHooks({ if (stableSubscriptionOptions !== lastSubscriptionOptions) { promiseRef.current?.updateSubscriptionOptions( - stableSubscriptionOptions + stableSubscriptionOptions, ) } }, [stableSubscriptionOptions]) @@ -859,7 +859,7 @@ export function buildHooks({ initiate(arg, { subscriptionOptions: subscriptionOptionsRef.current, forceRefetch: !preferCacheValue, - }) + }), ) setArg(arg) @@ -867,7 +867,7 @@ export function buildHooks({ return promise! }, - [dispatch, initiate] + [dispatch, initiate], ) /* cleanup on unmount */ @@ -889,7 +889,7 @@ export function buildHooks({ const useQueryState: UseQueryState = ( arg: any, - { skip = false, selectFromResult } = {} + { skip = false, selectFromResult } = {}, ) => { const { select } = api.endpoints[name] as ApiEndpointQuery< QueryDefinition, @@ -899,7 +899,7 @@ export function buildHooks({ skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], - name + name, ) type ApiRootState = Parameters>[0] @@ -919,9 +919,9 @@ export function buildHooks({ memoizeOptions: { resultEqualityCheck: shallowEqual, }, - } + }, ), - [select, stableArg] + [select, stableArg], ) const querySelector: Selector = useMemo( @@ -931,19 +931,19 @@ export function buildHooks({ devModeChecks: { identityFunctionCheck: 'never' }, }) : selectDefaultResult, - [selectDefaultResult, selectFromResult] + [selectDefaultResult, selectFromResult], ) const currentState = useSelector( (state: RootState) => querySelector(state, lastValue.current), - shallowEqual + shallowEqual, ) const store = useStore>() const newLastValue = selectDefaultResult( store.getState(), - lastValue.current + lastValue.current, ) useIsomorphicLayoutEffect(() => { lastValue.current = newLastValue @@ -966,7 +966,7 @@ export function buildHooks({ const info = useMemo(() => ({ lastArg: arg }), [arg]) return useMemo( () => [trigger, queryStateResults, info], - [trigger, queryStateResults, info] + [trigger, queryStateResults, info], ) }, useQuery(arg, options) { @@ -985,7 +985,7 @@ export function buildHooks({ return useMemo( () => ({ ...queryStateResults, ...querySubscriptionResults }), - [queryStateResults, querySubscriptionResults] + [queryStateResults, querySubscriptionResults], ) }, } @@ -1006,7 +1006,7 @@ export function buildHooks({ promise?.reset() } }, - [promise] + [promise], ) const triggerMutation = useCallback( @@ -1015,20 +1015,20 @@ export function buildHooks({ setPromise(promise) return promise }, - [dispatch, initiate, fixedCacheKey] + [dispatch, initiate, fixedCacheKey], ) const { requestId } = promise || {} const selectDefaultResult = useMemo( () => select({ fixedCacheKey, requestId: promise?.requestId }), - [fixedCacheKey, promise, select] + [fixedCacheKey, promise, select], ) const mutationSelector = useMemo( (): Selector, any> => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, - [selectFromResult, selectDefaultResult] + [selectFromResult, selectDefaultResult], ) const currentState = useSelector(mutationSelector, shallowEqual) @@ -1044,7 +1044,7 @@ export function buildHooks({ api.internalActions.removeMutationResult({ requestId, fixedCacheKey, - }) + }), ) } }) @@ -1071,12 +1071,12 @@ export function buildHooks({ const finalState = useMemo( () => ({ ...currentState, originalArgs, reset }), - [currentState, originalArgs, reset] + [currentState, originalArgs, reset], ) return useMemo( () => [triggerMutation, finalState] as const, - [triggerMutation, finalState] + [triggerMutation, finalState], ) } } diff --git a/packages/toolkit/src/query/react/index.ts b/packages/toolkit/src/query/react/index.ts index 437fc4287c..b9acba6b6b 100644 --- a/packages/toolkit/src/query/react/index.ts +++ b/packages/toolkit/src/query/react/index.ts @@ -10,7 +10,7 @@ export { ApiProvider } from './ApiProvider' const createApi = /* @__PURE__ */ buildCreateApi( coreModule(), - reactHooksModule() + reactHooksModule(), ) export type { diff --git a/packages/toolkit/src/query/react/module.ts b/packages/toolkit/src/query/react/module.ts index 68bcddb253..fed0b3d7a9 100644 --- a/packages/toolkit/src/query/react/module.ts +++ b/packages/toolkit/src/query/react/module.ts @@ -37,7 +37,7 @@ declare module '@reduxjs/toolkit/query' { // eslint-disable-next-line @typescript-eslint/no-unused-vars ReducerPath extends string, // eslint-disable-next-line @typescript-eslint/no-unused-vars - TagTypes extends string + TagTypes extends string, > { [reactHooksModuleName]: { /** @@ -53,18 +53,18 @@ declare module '@reduxjs/toolkit/query' { > ? QueryHooks : Definitions[K] extends MutationDefinition - ? MutationHooks - : never + ? MutationHooks + : never } /** * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint. */ usePrefetch>( endpointName: EndpointName, - options?: PrefetchOptions + options?: PrefetchOptions, ): ( arg: QueryArgFrom, - options?: PrefetchOptions + options?: PrefetchOptions, ) => void } & HooksWithUniqueNames } @@ -160,7 +160,7 @@ export const reactHooksModule = ({ if (!warned) { console.warn( 'As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:' + - '\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`' + '\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`', ) warned = true } @@ -175,8 +175,8 @@ export const reactHooksModule = ({ `When using custom hooks for context, all ${ hookNames.length } hooks need to be provided: ${hookNames.join( - ', ' - )}.\nHook ${hookName} was either not provided or not a function.` + ', ', + )}.\nHook ${hookName} was either not provided or not a function.`, ) } } diff --git a/packages/toolkit/src/query/react/useSerializedStableValue.ts b/packages/toolkit/src/query/react/useSerializedStableValue.ts index 52f87d7158..95bc62af78 100644 --- a/packages/toolkit/src/query/react/useSerializedStableValue.ts +++ b/packages/toolkit/src/query/react/useSerializedStableValue.ts @@ -6,7 +6,7 @@ export function useStableQueryArgs( queryArgs: T, serialize: SerializeQueryArgs, endpointDefinition: EndpointDefinition, - endpointName: string + endpointName: string, ) { const incoming = useMemo( () => ({ @@ -16,7 +16,7 @@ export function useStableQueryArgs( ? serialize({ queryArgs, endpointDefinition, endpointName }) : queryArgs, }), - [queryArgs, serialize, endpointDefinition, endpointName] + [queryArgs, serialize, endpointDefinition, endpointName], ) const cache = useRef(incoming) useEffect(() => { diff --git a/packages/toolkit/src/query/retry.ts b/packages/toolkit/src/query/retry.ts index 7bd960c699..3e5015d858 100644 --- a/packages/toolkit/src/query/retry.ts +++ b/packages/toolkit/src/query/retry.ts @@ -26,7 +26,7 @@ async function defaultBackoff(attempt: number = 0, maxRetries: number = 5) { const timeout = ~~((Math.random() + 0.4) * (300 << attempts)) // Force a positive int in the case we make this an option await new Promise((resolve) => - setTimeout((res: any) => resolve(res), timeout) + setTimeout((res: any) => resolve(res), timeout), ) } @@ -37,7 +37,7 @@ type RetryConditionFunction = ( attempt: number baseQueryApi: BaseQueryApi extraOptions: BaseQueryExtraOptions & RetryOptions - } + }, ) => boolean export type RetryOptions = { diff --git a/packages/toolkit/src/query/tests/apiProvider.test.tsx b/packages/toolkit/src/query/tests/apiProvider.test.tsx index 5b10573877..80101a8386 100644 --- a/packages/toolkit/src/query/tests/apiProvider.test.tsx +++ b/packages/toolkit/src/query/tests/apiProvider.test.tsx @@ -42,18 +42,18 @@ describe('ApiProvider', () => { const { getByText, getByTestId } = render( - + , ) await waitFor(() => - expect(getByTestId('isFetching').textContent).toBe('false') + expect(getByTestId('isFetching').textContent).toBe('false'), ) fireEvent.click(getByText('Increment value')) await waitFor(() => - expect(getByTestId('isFetching').textContent).toBe('true') + expect(getByTestId('isFetching').textContent).toBe('true'), ) await waitFor(() => - expect(getByTestId('isFetching').textContent).toBe('false') + expect(getByTestId('isFetching').textContent).toBe('false'), ) fireEvent.click(getByText('Increment value')) // Being that nothing has changed in the args, this should never fire. @@ -64,10 +64,10 @@ describe('ApiProvider', () => { render( null })}> child - - ) + , + ), ).toThrowErrorMatchingInlineSnapshot( - `[Error: Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.]` + `[Error: Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.]`, ) }) }) diff --git a/packages/toolkit/src/query/tests/buildCreateApi.test.tsx b/packages/toolkit/src/query/tests/buildCreateApi.test.tsx index 9149d9c3b1..9a443c9350 100644 --- a/packages/toolkit/src/query/tests/buildCreateApi.test.tsx +++ b/packages/toolkit/src/query/tests/buildCreateApi.test.tsx @@ -28,7 +28,7 @@ describe('buildCreateApi', () => { useSelector: createSelectorHook(MyContext), useStore: createStoreHook(MyContext), }, - }) + }), ) const api = customCreateApi({ @@ -78,7 +78,7 @@ describe('buildCreateApi', () => { expect(getRenderCount()).toBe(2) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('false') + expect(screen.getByTestId('isFetching').textContent).toBe('false'), ) expect(getRenderCount()).toBe(3) }) @@ -93,7 +93,7 @@ describe('buildCreateApi', () => { useDispatch: createDispatchHook(MyContext), useSelector: createSelectorHook(MyContext), }, - }) + }), ) } @@ -101,7 +101,7 @@ describe('buildCreateApi', () => { ` [Error: When using custom hooks for context, all 3 hooks need to be provided: useDispatch, useSelector, useStore. Hook useStore was either not provided or not a function.] - ` + `, ) }) test('allows passing createSelector instance', async () => { @@ -109,7 +109,7 @@ describe('buildCreateApi', () => { const createSelector = createSelectorCreator(memoize) const createApi = buildCreateApi( coreModule({ createSelector }), - reactHooksModule({ createSelector }) + reactHooksModule({ createSelector }), ) const api = createApi({ baseQuery: async (arg: any) => { @@ -159,7 +159,7 @@ describe('buildCreateApi', () => { render(, { wrapper: Wrapper }) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('false') + expect(screen.getByTestId('isFetching').textContent).toBe('false'), ) // select() + selectFromResult diff --git a/packages/toolkit/src/query/tests/buildInitiate.test.tsx b/packages/toolkit/src/query/tests/buildInitiate.test.tsx index 3ac8184995..f7022acf30 100644 --- a/packages/toolkit/src/query/tests/buildInitiate.test.tsx +++ b/packages/toolkit/src/query/tests/buildInitiate.test.tsx @@ -30,7 +30,7 @@ let isRequestSubscribed: SubscriptionSelectors['isRequestSubscribed'] beforeEach(() => { ;({ getSubscriptions, isRequestSubscribed } = storeRef.store.dispatch( - api.internalActions.internal_getRTKQSubscriptions() + api.internalActions.internal_getRTKQSubscriptions(), ) as unknown as SubscriptionSelectors) }) @@ -45,7 +45,7 @@ test('multiple synchonrous initiate calls with pre-existing cache entry', async const secondValuePromise = store.dispatch(api.endpoints.increment.initiate()) // and one with a forced refresh const thirdValuePromise = store.dispatch( - api.endpoints.increment.initiate(undefined, { forceRefetch: true }) + api.endpoints.increment.initiate(undefined, { forceRefetch: true }), ) // and another increment const fourthValuePromise = store.dispatch(api.endpoints.increment.initiate()) @@ -74,16 +74,16 @@ describe('calling initiate without a cache entry, with subscribe: false still re const { store, api } = storeRef calls = 0 const promise = store.dispatch( - api.endpoints.increment.initiate(undefined, { subscribe: false }) + api.endpoints.increment.initiate(undefined, { subscribe: false }), ) expect(isRequestSubscribed('increment(undefined)', promise.requestId)).toBe( - false + false, ) expect( isRequestSubscribed( 'increment(undefined)', - `${promise.requestId}_running` - ) + `${promise.requestId}_running`, + ), ).toBe(true) await expect(promise).resolves.toMatchObject({ @@ -93,8 +93,8 @@ describe('calling initiate without a cache entry, with subscribe: false still re expect( isRequestSubscribed( 'increment(undefined)', - `${promise.requestId}_running` - ) + `${promise.requestId}_running`, + ), ).toBe(false) }) @@ -102,20 +102,20 @@ describe('calling initiate without a cache entry, with subscribe: false still re const { store, api } = storeRef calls = 0 const promise = store.dispatch( - api.endpoints.failing.initiate(undefined, { subscribe: false }) + api.endpoints.failing.initiate(undefined, { subscribe: false }), ) expect(isRequestSubscribed('failing(undefined)', promise.requestId)).toBe( - false + false, ) expect( - isRequestSubscribed('failing(undefined)', `${promise.requestId}_running`) + isRequestSubscribed('failing(undefined)', `${promise.requestId}_running`), ).toBe(true) await expect(promise).resolves.toMatchObject({ status: 'rejected', }) expect( - isRequestSubscribed('failing(undefined)', `${promise.requestId}_running`) + isRequestSubscribed('failing(undefined)', `${promise.requestId}_running`), ).toBe(false) }) }) diff --git a/packages/toolkit/src/query/tests/buildMiddleware.test.tsx b/packages/toolkit/src/query/tests/buildMiddleware.test.tsx index 2ba752d3c0..0e52cb0cd1 100644 --- a/packages/toolkit/src/query/tests/buildMiddleware.test.tsx +++ b/packages/toolkit/src/query/tests/buildMiddleware.test.tsx @@ -38,7 +38,7 @@ it('invalidates the specified tags', async () => { expect(storeRef.store.getState().actions).toMatchSequence( api.internalActions.middlewareRegistered.match, getBanana.matchPending, - getBanana.matchFulfilled + getBanana.matchFulfilled, ) await storeRef.store.dispatch(api.util.invalidateTags(['Banana', 'Bread'])) @@ -67,6 +67,6 @@ it('invalidates the specified tags', async () => { getBread.matchFulfilled, api.util.invalidateTags.match, getBread.matchPending, - getBread.matchFulfilled + getBread.matchFulfilled, ) }) diff --git a/packages/toolkit/src/query/tests/buildSlice.test.ts b/packages/toolkit/src/query/tests/buildSlice.test.ts index 3b5efe268f..72ac45b7a2 100644 --- a/packages/toolkit/src/query/tests/buildSlice.test.ts +++ b/packages/toolkit/src/query/tests/buildSlice.test.ts @@ -44,7 +44,7 @@ describe('buildSlice', () => { const initialState = storeRef.store.getState() await storeRef.store.dispatch( - getUser.initiate(1, { subscriptionOptions: { pollingInterval: 10 } }) + getUser.initiate(1, { subscriptionOptions: { pollingInterval: 10 } }), ) const initialQueryState = { @@ -95,10 +95,10 @@ describe('buildSlice', () => { await storeRef.store.dispatch(getUser.initiate(1)) expect( - api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']) + api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']), ).toHaveLength(1) expect( - api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']) + api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']), ).toHaveLength(0) shouldApiResponseSuccess = false @@ -108,10 +108,10 @@ describe('buildSlice', () => { await delay(10) expect( - api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']) + api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']), ).toHaveLength(0) expect( - api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']) + api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']), ).toHaveLength(1) }) }) diff --git a/packages/toolkit/src/query/tests/buildThunks.test.tsx b/packages/toolkit/src/query/tests/buildThunks.test.tsx index aa4afebd51..d68a0e9800 100644 --- a/packages/toolkit/src/query/tests/buildThunks.test.tsx +++ b/packages/toolkit/src/query/tests/buildThunks.test.tsx @@ -95,7 +95,7 @@ describe('re-triggering behavior on arg change', () => { { wrapper: withProvider(store), initialProps: 5, - } + }, ) await waitFor(() => { @@ -127,7 +127,7 @@ describe('re-triggering behavior on arg change', () => { { wrapper: withProvider(store), initialProps: { name: 'Bob', likes: 'iceCream' }, - } + }, ) await waitFor(() => { @@ -160,7 +160,7 @@ describe('re-triggering behavior on arg change', () => { { wrapper: withProvider(store), initialProps: { person: { name } }, - } + }, ) await waitFor(() => { @@ -183,7 +183,7 @@ describe('re-triggering behavior on arg change', () => { { wrapper: withProvider(store), initialProps: { name: 'Tim', likes: 'Bananas' }, - } + }, ) await waitFor(() => { diff --git a/packages/toolkit/src/query/tests/cacheCollection.test.ts b/packages/toolkit/src/query/tests/cacheCollection.test.ts index 28e090a4b4..936ae82044 100644 --- a/packages/toolkit/src/query/tests/cacheCollection.test.ts +++ b/packages/toolkit/src/query/tests/cacheCollection.test.ts @@ -27,7 +27,7 @@ test(`query: await cleanup, defaults`, async () => { query: () => '/success', }), }), - }) + }), ) const promise = store.dispatch(api.endpoints.query.initiate('arg')) @@ -49,7 +49,7 @@ test(`query: await cleanup, keepUnusedDataFor set`, async () => { }), }), keepUnusedDataFor: 29, - }) + }), ) const promise = store.dispatch(api.endpoints.query.initiate('arg')) @@ -71,7 +71,7 @@ test(`query: handles large keepUnuseDataFor values over 32-bit ms`, async () => }), }), keepUnusedDataFor: THIRTY_TWO_BIT_MAX_TIMER_SECONDS - 10, - }) + }), ) const promise = store.dispatch(api.endpoints.query.initiate('arg')) @@ -113,7 +113,7 @@ describe(`query: await cleanup, keepUnusedDataFor set`, () => { }), }), keepUnusedDataFor: 29, - }) + }), ) test('global keepUnusedDataFor', async () => { @@ -162,13 +162,13 @@ function storeForApi< reducer: Reducer middleware: Middleware util: { resetApiState(): any } - } + }, >(api: A) { const store = configureStore({ reducer: { api: api.reducer }, middleware: (gdm) => gdm({ serializableCheck: false, immutableCheck: false }).concat( - api.middleware + api.middleware, ), enhancers: (gde) => gde({ diff --git a/packages/toolkit/src/query/tests/cleanup.test.tsx b/packages/toolkit/src/query/tests/cleanup.test.tsx index eff34b400d..dc3d8fcbe1 100644 --- a/packages/toolkit/src/query/tests/cleanup.test.tsx +++ b/packages/toolkit/src/query/tests/cleanup.test.tsx @@ -51,7 +51,7 @@ test('data stays in store when component stays rendered', async () => { render(, { wrapper: storeRef.wrapper }) await waitFor(() => - expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled) + expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled), ) vi.advanceTimersByTime(120_000) @@ -64,7 +64,7 @@ test('data is removed from store after 60 seconds', async () => { const { unmount } = render(, { wrapper: storeRef.wrapper }) await waitFor(() => - expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled) + expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled), ) unmount() @@ -87,7 +87,7 @@ test('data stays in store when component stays rendered while data for another c , - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) await waitFor(() => { expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled) @@ -117,7 +117,7 @@ test('data stays in store when one component requiring the data stays in the sto , - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) await waitFor(() => { expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled) @@ -168,7 +168,7 @@ test('Minimizes the number of subscription dispatches when multiple components a }) const { getSubscriptionCount } = storeRef.store.dispatch( - api.internalActions.internal_getRTKQSubscriptions() + api.internalActions.internal_getRTKQSubscriptions(), ) as unknown as SubscriptionSelectors const NUM_LIST_ITEMS = 1000 diff --git a/packages/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts b/packages/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts index 45bd57cbb8..fa9ad3b72b 100644 --- a/packages/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts +++ b/packages/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts @@ -9,7 +9,7 @@ test('string arg', () => { endpointDefinition, endpointName, queryArgs: 'arg', - }) + }), ).toMatchInlineSnapshot(`"test("arg")"`) }) @@ -19,7 +19,7 @@ test('number arg', () => { endpointDefinition, endpointName, queryArgs: 5, - }) + }), ).toMatchInlineSnapshot(`"test(5)"`) }) @@ -29,7 +29,7 @@ test('simple object arg is sorted', () => { endpointDefinition, endpointName, queryArgs: { name: 'arg', age: 5 }, - }) + }), ).toMatchInlineSnapshot(`"test({"age":5,"name":"arg"})"`) }) @@ -39,9 +39,9 @@ test('nested object arg is sorted recursively', () => { endpointDefinition, endpointName, queryArgs: { name: { last: 'Split', first: 'Banana' }, age: 5 }, - }) + }), ).toMatchInlineSnapshot( - `"test({"age":5,"name":{"first":"Banana","last":"Split"}})"` + `"test({"age":5,"name":{"first":"Banana","last":"Split"}})"`, ) }) @@ -70,7 +70,7 @@ test('Fully serializes a deeply nested object', () => { queryArgs: nestedObj, }) expect(res).toMatchInlineSnapshot( - `"test({"a":{"a1":{"a11":{"a111":1}}},"b":{"b1":{"b11":2},"b2":{"b21":3}}})"` + `"test({"a":{"a1":{"a11":{"a111":1}}},"b":{"b1":{"b11":2},"b2":{"b21":3}}})"`, ) }) diff --git a/packages/toolkit/src/query/tests/devWarnings.test.tsx b/packages/toolkit/src/query/tests/devWarnings.test.tsx index df8339f5f3..f0b61d3518 100644 --- a/packages/toolkit/src/query/tests/devWarnings.test.tsx +++ b/packages/toolkit/src/query/tests/devWarnings.test.tsx @@ -110,7 +110,7 @@ describe('missing middleware', () => { } expect(doDispatch1).toThrowError(reMatchMissingMiddlewareError) expect(doDispatch2).toThrowError( - /Warning: Middleware for RTK-Query API at reducerPath "api2" has not been added to the store/ + /Warning: Middleware for RTK-Query API at reducerPath "api2" has not been added to the store/, ) }) }) @@ -141,7 +141,7 @@ describe('missing reducer', () => { expect(getLog().log).toBe( shouldWarn ? 'Error: No data found at `state.api`. Did you forget to add the reducer to the store?' - : '' + : '', ) }) }) @@ -166,7 +166,7 @@ describe('missing reducer', () => { // @ts-expect-error api1.endpoints.q1.select(undefined)(store.getState()) expect(getLog().log).toBe( - 'Error: No data found at `state.api`. Did you forget to add the reducer to the store?' + 'Error: No data found at `state.api`. Did you forget to add the reducer to the store?', ) }) @@ -181,7 +181,7 @@ describe('missing reducer', () => { // @ts-expect-error api2.endpoints.q1.select(undefined)(store.getState()) expect(getLog().log).toBe( - 'Error: No data found at `state.api`. Did you forget to add the reducer to the store?\nError: No data found at `state.api2`. Did you forget to add the reducer to the store?' + 'Error: No data found at `state.api`. Did you forget to add the reducer to the store?\nError: No data found at `state.api2`. Did you forget to add the reducer to the store?', ) }) }) @@ -197,7 +197,7 @@ test('warns for reducer and also throws error if everything is missing', async ( } expect(doDispatch).toThrowError(reMatchMissingMiddlewareError) expect(getLog().log).toBe( - 'Error: No data found at `state.api`. Did you forget to add the reducer to the store?' + 'Error: No data found at `state.api`. Did you forget to add the reducer to the store?', ) }) @@ -218,7 +218,7 @@ describe('warns on multiple apis using the same `reducerPath`', () => { expect(getLog().log).toBe( `There is a mismatch between slice and middleware for the reducerPath "api". You can only have one api per reducer path, this will lead to crashes in various situations! -If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` +If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`, ) }) @@ -240,7 +240,7 @@ You can only have one api per reducer path, this will lead to crashes in various If you have multiple apis, you *have* to specify the reducerPath option when using createApi! There is a mismatch between slice and middleware for the reducerPath "api". You can only have one api per reducer path, this will lead to crashes in various situations! -If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` +If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`, ) }) @@ -259,7 +259,7 @@ If you have multiple apis, you *have* to specify the reducerPath option when usi expect(getLog().log).toBe( `There is a mismatch between slice and middleware for the reducerPath "api". You can only have one api per reducer path, this will lead to crashes in various situations! -If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` +If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`, ) }) @@ -285,7 +285,7 @@ If you have multiple apis, you *have* to specify the reducerPath option when usi expect(getLog().log).toBe( `There is a mismatch between slice and middleware for the reducerPath "api". You can only have one api per reducer path, this will lead to crashes in various situations! -If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` +If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`, ) }) }) diff --git a/packages/toolkit/src/query/tests/errorHandling.test.tsx b/packages/toolkit/src/query/tests/errorHandling.test.tsx index 04ce766fb2..83338ec722 100644 --- a/packages/toolkit/src/query/tests/errorHandling.test.tsx +++ b/packages/toolkit/src/query/tests/errorHandling.test.tsx @@ -36,7 +36,7 @@ const storeRef = setupApiStore(api) const failQueryOnce = http.get( '/query', () => HttpResponse.json({ value: 'failed' }, { status: 500 }), - { once: true } + { once: true }, ) describe('fetchBaseQuery', () => { @@ -57,7 +57,7 @@ describe('fetchBaseQuery', () => { }) test('success', async () => { await expect( - baseQuery('/success', commonBaseQueryApiArgs, {}) + baseQuery('/success', commonBaseQueryApiArgs, {}), ).resolves.toEqual({ data: { value: 'success' }, meta: { @@ -69,7 +69,7 @@ describe('fetchBaseQuery', () => { test('error', async () => { server.use(failQueryOnce) await expect( - baseQuery('/error', commonBaseQueryApiArgs, {}) + baseQuery('/error', commonBaseQueryApiArgs, {}), ).resolves.toEqual({ error: { data: { value: 'error' }, @@ -87,8 +87,8 @@ describe('query error handling', () => { test('success', async () => { server.use( http.get('https://example.com/query', () => - HttpResponse.json({ value: 'success' }) - ) + HttpResponse.json({ value: 'success' }), + ), ) const { result } = renderHook(() => api.endpoints.query.useQuery({}), { wrapper: storeRef.wrapper, @@ -101,15 +101,15 @@ describe('query error handling', () => { isError: false, isSuccess: true, data: { value: 'success' }, - }) + }), ) }) test('error', async () => { server.use( http.get('https://example.com/query', () => - HttpResponse.json({ value: 'error' }, { status: 500 }) - ) + HttpResponse.json({ value: 'error' }, { status: 500 }), + ), ) const { result } = renderHook(() => api.endpoints.query.useQuery({}), { wrapper: storeRef.wrapper, @@ -125,15 +125,15 @@ describe('query error handling', () => { status: 500, data: { value: 'error' }, }, - }) + }), ) }) test('success -> error', async () => { server.use( http.get('https://example.com/query', () => - HttpResponse.json({ value: 'success' }) - ) + HttpResponse.json({ value: 'success' }), + ), ) const { result } = renderHook(() => api.endpoints.query.useQuery({}), { wrapper: storeRef.wrapper, @@ -146,15 +146,15 @@ describe('query error handling', () => { isError: false, isSuccess: true, data: { value: 'success' }, - }) + }), ) server.use( http.get( 'https://example.com/query', () => HttpResponse.json({ value: 'error' }, { status: 500 }), - { once: true } - ) + { once: true }, + ), ) act(() => void result.current.refetch()) @@ -171,22 +171,22 @@ describe('query error handling', () => { }, // last data will stay available data: { value: 'success' }, - }) + }), ) }) test('error -> success', async () => { server.use( http.get('https://example.com/query', () => - HttpResponse.json({ value: 'success' }) - ) + HttpResponse.json({ value: 'success' }), + ), ) server.use( http.get( 'https://example.com/query', () => HttpResponse.json({ value: 'error' }, { status: 500 }), - { once: true } - ) + { once: true }, + ), ) const { result } = renderHook(() => api.endpoints.query.useQuery({}), { wrapper: storeRef.wrapper, @@ -202,7 +202,7 @@ describe('query error handling', () => { status: 500, data: { value: 'error' }, }, - }) + }), ) act(() => void result.current.refetch()) @@ -214,7 +214,7 @@ describe('query error handling', () => { isError: false, isSuccess: true, data: { value: 'success' }, - }) + }), ) }) }) @@ -223,8 +223,8 @@ describe('mutation error handling', () => { test('success', async () => { server.use( http.post('https://example.com/mutation', () => - HttpResponse.json({ value: 'success' }) - ) + HttpResponse.json({ value: 'success' }), + ), ) const { result } = renderHook(() => api.endpoints.mutation.useMutation(), { wrapper: storeRef.wrapper, @@ -241,15 +241,15 @@ describe('mutation error handling', () => { isError: false, isSuccess: true, data: { value: 'success' }, - }) + }), ) }) test('error', async () => { server.use( http.post('https://example.com/mutation', () => - HttpResponse.json({ value: 'error' }, { status: 500 }) - ) + HttpResponse.json({ value: 'error' }, { status: 500 }), + ), ) const { result } = renderHook(() => api.endpoints.mutation.useMutation(), { wrapper: storeRef.wrapper, @@ -269,15 +269,15 @@ describe('mutation error handling', () => { status: 500, data: { value: 'error' }, }, - }) + }), ) }) test('success -> error', async () => { server.use( http.post('https://example.com/mutation', () => - HttpResponse.json({ value: 'success' }) - ) + HttpResponse.json({ value: 'success' }), + ), ) const { result } = renderHook(() => api.endpoints.mutation.useMutation(), { wrapper: storeRef.wrapper, @@ -295,7 +295,7 @@ describe('mutation error handling', () => { isError: false, isSuccess: true, data: { value: 'success' }, - }) + }), ) } @@ -303,8 +303,8 @@ describe('mutation error handling', () => { http.post( 'https://example.com/mutation', () => HttpResponse.json({ value: 'error' }, { status: 500 }), - { once: true } - ) + { once: true }, + ), ) { @@ -322,7 +322,7 @@ describe('mutation error handling', () => { status: 500, data: { value: 'error' }, }, - }) + }), ) expect(result.current[1].data).toBeUndefined() } @@ -331,15 +331,15 @@ describe('mutation error handling', () => { test('error -> success', async () => { server.use( http.post('https://example.com/mutation', () => - HttpResponse.json({ value: 'success' }) - ) + HttpResponse.json({ value: 'success' }), + ), ) server.use( http.post( 'https://example.com/mutation', () => HttpResponse.json({ value: 'error' }, { status: 500 }), - { once: true } - ) + { once: true }, + ), ) const { result } = renderHook(() => api.endpoints.mutation.useMutation(), { @@ -361,7 +361,7 @@ describe('mutation error handling', () => { status: 500, data: { value: 'error' }, }, - }) + }), ) } @@ -376,7 +376,7 @@ describe('mutation error handling', () => { isLoading: false, isError: false, isSuccess: true, - }) + }), ) expect(result.current[1].error).toBeUndefined() } @@ -386,7 +386,7 @@ describe('mutation error handling', () => { describe('custom axios baseQuery', () => { const axiosBaseQuery = ( - { baseUrl }: { baseUrl: string } = { baseUrl: '' } + { baseUrl }: { baseUrl: string } = { baseUrl: '' }, ): BaseQueryFn< { url: string @@ -452,8 +452,8 @@ describe('custom axios baseQuery', () => { test('axios errors behave as expected', async () => { server.use( http.get('https://example.com/success', () => - HttpResponse.json({ value: 'error' }, { status: 500 }) - ) + HttpResponse.json({ value: 'error' }, { status: 500 }), + ), ) const { result } = renderHook(() => api.endpoints.query.useQuery(), { wrapper: storeRef.wrapper, @@ -466,7 +466,7 @@ describe('custom axios baseQuery', () => { isError: true, isSuccess: false, error: { status: 500, data: { value: 'error' } }, - }) + }), ) }) }) @@ -493,8 +493,8 @@ describe('error handling in a component', () => { http.get( 'https://example.com/success', () => HttpResponse.json(mockErrorResponse, { status: 500 }), - { once: true } - ) + { once: true }, + ), ) function User() { @@ -529,36 +529,36 @@ describe('error handling in a component', () => { render(, { wrapper: storeRef.wrapper }) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) fireEvent.click(screen.getByText('Update User')) expect(screen.getByTestId('isLoading').textContent).toBe('true') await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) // Make sure the hook and the unwrapped action return the same things in an error state await waitFor(() => expect(screen.getByTestId('error').textContent).toEqual( - screen.getByTestId('manuallySetError').textContent - ) + screen.getByTestId('manuallySetError').textContent, + ), ) fireEvent.click(screen.getByText('Update User')) expect(screen.getByTestId('isLoading').textContent).toBe('true') await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('error').textContent).toBeFalsy() + expect(screen.getByTestId('error').textContent).toBeFalsy(), ) await waitFor(() => - expect(screen.getByTestId('manuallySetError').textContent).toBeFalsy() + expect(screen.getByTestId('manuallySetError').textContent).toBeFalsy(), ) await waitFor(() => expect(screen.getByTestId('data').textContent).toEqual( - JSON.stringify(mockSuccessResponse) - ) + JSON.stringify(mockSuccessResponse), + ), ) }) @@ -576,7 +576,7 @@ describe('error handling in a component', () => { > act(() => { mutationqueryFulfilled = dispatch( - api.endpoints.update.initiate({}, { track }) + api.endpoints.update.initiate({}, { track }), ) }) const result = await mutationqueryFulfilled! @@ -598,7 +598,7 @@ describe('error handling in a component', () => { > act(() => { mutationqueryFulfilled = dispatch( - api.endpoints.failedUpdate.initiate({}, { track }) + api.endpoints.failedUpdate.initiate({}, { track }), ) }) const result = await mutationqueryFulfilled! @@ -622,7 +622,7 @@ describe('error handling in a component', () => { > act(() => { mutationqueryFulfilled = dispatch( - api.endpoints.update.initiate({}, { track }) + api.endpoints.update.initiate({}, { track }), ) }) const result = await mutationqueryFulfilled!.unwrap() @@ -644,7 +644,7 @@ describe('error handling in a component', () => { > act(() => { mutationqueryFulfilled = dispatch( - api.endpoints.failedUpdate.initiate({}, { track }) + api.endpoints.failedUpdate.initiate({}, { track }), ) }) const unwrappedPromise = mutationqueryFulfilled!.unwrap() diff --git a/packages/toolkit/src/query/tests/fakeBaseQuery.test.tsx b/packages/toolkit/src/query/tests/fakeBaseQuery.test.tsx index f049e970c0..cddf0c051f 100644 --- a/packages/toolkit/src/query/tests/fakeBaseQuery.test.tsx +++ b/packages/toolkit/src/query/tests/fakeBaseQuery.test.tsx @@ -128,7 +128,7 @@ test('fakeBaseQuery throws when invoking query', async () => { result = await store.dispatch(thunk) }).toHaveConsoleOutput( `An unhandled error occurred processing a request for the endpoint "withQuery". - In the case of an unhandled error, no tags will be "provided" or "invalidated". [Error: When using \`fakeBaseQuery\`, all queries & mutations must use the \`queryFn\` definition syntax.]` + In the case of an unhandled error, no tags will be "provided" or "invalidated". [Error: When using \`fakeBaseQuery\`, all queries & mutations must use the \`queryFn\` definition syntax.]`, ) expect(result!.error).toEqual({ diff --git a/packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx b/packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx index 08e9d6a8f1..07bda8f612 100644 --- a/packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx +++ b/packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx @@ -146,14 +146,14 @@ describe('fetchBaseQuery', () => { http.get( 'https://example.com/success', () => HttpResponse.text(`this is not json!`), - { once: true } - ) + { once: true }, + ), ) const req = baseQuery( { url: '/success', responseHandler: 'text' }, commonBaseQueryApi, - {} + {}, ) expect(req).toBeInstanceOf(Promise) const res = await req @@ -168,8 +168,8 @@ describe('fetchBaseQuery', () => { http.get( 'https://example.com/success', () => HttpResponse.text(`this is not json!`), - { once: true } - ) + { once: true }, + ), ) const req = baseQuery('/success', commonBaseQueryApi, {}) @@ -191,8 +191,8 @@ describe('fetchBaseQuery', () => { http.get( 'https://example.com/success', () => HttpResponse.text(`this is not json!`), - { once: true } - ) + { once: true }, + ), ) const req = baseQuery( @@ -201,13 +201,13 @@ describe('fetchBaseQuery', () => { responseHandler: 'content-type', }, commonBaseQueryApi, - {} + {}, ) expect(req).toBeInstanceOf(Promise) const res = await req expect(res).toBeInstanceOf(Object) expect(res.meta?.response?.headers.get('content-type')).toEqual( - 'text/plain' + 'text/plain', ) expect(res.meta?.request).toBeInstanceOf(Request) expect(res.meta?.response).toBeInstanceOf(Object) @@ -219,8 +219,8 @@ describe('fetchBaseQuery', () => { http.get( 'https://example.com/success', () => HttpResponse.json(`this will become json!`), - { once: true } - ) + { once: true }, + ), ) const req = baseQuery( @@ -229,13 +229,13 @@ describe('fetchBaseQuery', () => { responseHandler: 'content-type', }, commonBaseQueryApi, - {} + {}, ) expect(req).toBeInstanceOf(Promise) const res = await req expect(res).toBeInstanceOf(Object) expect(res.meta?.response?.headers.get('content-type')).toEqual( - 'application/json' + 'application/json', ) expect(res.meta?.request).toBeInstanceOf(Request) expect(res.meta?.response).toBeInstanceOf(Object) @@ -245,14 +245,14 @@ describe('fetchBaseQuery', () => { it('server error: should fail normally with a 500 status ("text" responseHandler)', async () => { server.use( http.get('https://example.com/error', () => - HttpResponse.text(`this is not json!`, { status: 500 }) - ) + HttpResponse.text(`this is not json!`, { status: 500 }), + ), ) const req = baseQuery( { url: '/error', responseHandler: 'text' }, commonBaseQueryApi, - {} + {}, ) expect(req).toBeInstanceOf(Promise) const res = await req @@ -269,14 +269,14 @@ describe('fetchBaseQuery', () => { const serverResponse = 'Internal Server Error' server.use( http.get('https://example.com/error', () => - HttpResponse.text(serverResponse, { status: 500 }) - ) + HttpResponse.text(serverResponse, { status: 500 }), + ), ) const req = baseQuery( { url: '/error', responseHandler: 'content-type' }, commonBaseQueryApi, - {} + {}, ) expect(req).toBeInstanceOf(Promise) const res = await req @@ -284,7 +284,7 @@ describe('fetchBaseQuery', () => { expect(res.meta?.request).toBeInstanceOf(Request) expect(res.meta?.response).toBeInstanceOf(Object) expect(res.meta?.response?.headers.get('content-type')).toEqual( - 'text/plain' + 'text/plain', ) expect(res.error).toEqual({ status: 500, @@ -298,14 +298,14 @@ describe('fetchBaseQuery', () => { } server.use( http.get('https://example.com/error', () => - HttpResponse.json(serverResponse, { status: 500 }) - ) + HttpResponse.json(serverResponse, { status: 500 }), + ), ) const req = baseQuery( { url: '/error', responseHandler: 'content-type' }, commonBaseQueryApi, - {} + {}, ) expect(req).toBeInstanceOf(Promise) const res = await req @@ -313,7 +313,7 @@ describe('fetchBaseQuery', () => { expect(res.meta?.request).toBeInstanceOf(Request) expect(res.meta?.response).toBeInstanceOf(Object) expect(res.meta?.response?.headers.get('content-type')).toEqual( - 'application/json' + 'application/json', ) expect(res.error).toEqual({ status: 500, @@ -324,8 +324,8 @@ describe('fetchBaseQuery', () => { it('server error: should fail gracefully (default="json" responseHandler)', async () => { server.use( http.get('https://example.com/error', () => - HttpResponse.text(`this is not json!`, { status: 500 }) - ) + HttpResponse.text(`this is not json!`, { status: 500 }), + ), ) const req = baseQuery('/error', commonBaseQueryApi, {}) @@ -353,7 +353,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', body: data, method: 'POST' }, { ...commonBaseQueryApi, type: 'mutation' }, - {} + {}, )) expect(request.headers['content-type']).toBe('application/json') @@ -367,7 +367,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', body: data, method: 'POST' }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['content-type']).toBe('application/json') @@ -388,7 +388,7 @@ describe('fetchBaseQuery', () => { headers: { 'content-type': 'text/html' }, }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['content-type']).toBe('text/html') @@ -407,7 +407,7 @@ describe('fetchBaseQuery', () => { headers: { 'content-type': 'text/html' }, }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['content-type']).toBe('text/html') @@ -429,7 +429,7 @@ describe('fetchBaseQuery', () => { method: 'POST', }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['content-type']).toBe('application/vnd.api+json') @@ -448,7 +448,7 @@ describe('fetchBaseQuery', () => { method: 'POST', }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['content-type']).toBe('application/json') @@ -469,7 +469,7 @@ describe('fetchBaseQuery', () => { method: 'POST', }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['content-type']).toBe('application/json') @@ -483,7 +483,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo' }, commonBaseQueryApi, - {} + {}, )) expect(request.url).toEqual(`${baseUrl}/echo`) @@ -496,7 +496,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', params }, commonBaseQueryApi, - {} + {}, )) expect(request.url).toEqual(`${baseUrl}/echo?a=1&b=true`) @@ -509,7 +509,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo?banana=pudding', params }, commonBaseQueryApi, - {} + {}, )) expect(request.url).toEqual(`${baseUrl}/echo?banana=pudding&a=1&b=true`) @@ -522,7 +522,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', params }, commonBaseQueryApi, - {} + {}, )) expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`) @@ -535,7 +535,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', params }, commonBaseQueryApi, - {} + {}, )) expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit&randy=null`) @@ -575,11 +575,11 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', params }, commonBaseQueryApi, - {} + {}, )) expect(request.url).toEqual( - `${baseUrl}/echo?someArray[]=a&someArray[]=b&someArray[]=c` + `${baseUrl}/echo?someArray[]=a&someArray[]=b&someArray[]=c`, ) }) @@ -607,7 +607,7 @@ describe('fetchBaseQuery', () => { headers: { 'content-type': 'application/vnd.hal+json' }, }, commonBaseQueryApi, - {} + {}, )) expect(request.body).toMatchObject(testBody) @@ -624,7 +624,7 @@ describe('fetchBaseQuery', () => { response.status === 200 && body.success === false ? false : true, }, commonBaseQueryApi, - {} + {}, ) expect(res.error).toEqual({ @@ -643,7 +643,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo' }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['fake']).toBe(defaultHeaders['fake']) @@ -656,7 +656,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', headers: { authorization: 'Bearer banana' } }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['authorization']).toBe('Bearer banana') @@ -676,7 +676,7 @@ describe('fetchBaseQuery', () => { }, }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['authorization']).toBe('Bearer banana') @@ -693,7 +693,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', headers: { fake, delete: '', delete2: '' } }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['fake']).toBe(fake) @@ -782,7 +782,7 @@ describe('fetchBaseQuery', () => { type: 'query', endpoint: '', }, - {} + {}, ) } @@ -806,7 +806,7 @@ describe('fetchBaseQuery', () => { fetchFn: fetchFn as any, prepareHeaders: ( headers, - { getState, extra, endpoint, type, forced } + { getState, extra, endpoint, type, forced }, ) => { _getState = getState _endpoint = endpoint @@ -838,7 +838,7 @@ describe('fetchBaseQuery', () => { forced: true, endpoint: 'someEndpointName', }, - {} + {}, ) } @@ -875,7 +875,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', headers: undefined }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['fake']).toBe(defaultHeaders['fake']) @@ -889,7 +889,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', headers: { banana } }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['banana']).toBe('1') @@ -904,7 +904,7 @@ describe('fetchBaseQuery', () => { ;({ data: request } = await baseQuery( { url: '/echo', headers: { banana } }, commonBaseQueryApi, - {} + {}, )) expect(request.headers['banana']).toBeUndefined() @@ -919,8 +919,8 @@ describe('fetchBaseQuery', () => { http.get( 'https://example.com/success', () => HttpResponse.text(`this is not json!`), - { once: true } - ) + { once: true }, + ), ) const globalizedBaseQuery = fetchBaseQuery({ @@ -932,7 +932,7 @@ describe('fetchBaseQuery', () => { const req = globalizedBaseQuery( { url: '/success' }, commonBaseQueryApi, - {} + {}, ) expect(req).toBeInstanceOf(Promise) const res = await req @@ -957,7 +957,7 @@ describe('fetchBaseQuery', () => { url: '/nonstandard-error', }, commonBaseQueryApi, - {} + {}, ) expect(res.error).toEqual({ @@ -985,8 +985,8 @@ describe('fetchBaseQuery', () => { headers: headersToObject(request.headers), }) }, - { once: true } - ) + { once: true }, + ), ) const globalizedBaseQuery = fetchBaseQuery({ @@ -998,7 +998,7 @@ describe('fetchBaseQuery', () => { const result = await globalizedBaseQuery( { url: '/empty1' }, commonBaseQueryApi, - {} + {}, ) expect(result?.error).toEqual({ @@ -1022,7 +1022,7 @@ describe('fetchFn', () => { ;({ data: request } = await baseQuery( { url: '/echo', params }, commonBaseQueryApi, - {} + {}, )) expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`) @@ -1059,13 +1059,13 @@ describe('FormData', () => { 'file', new Blob([JSON.stringify({ hello: 'there' }, null, 2)], { type: 'application/json', - }) + }), ) const res = await baseQuery( { url: '/echo', method: 'POST', body }, commonBaseQueryApi, - {} + {}, ) const request: any = res.data @@ -1085,7 +1085,7 @@ describe('still throws on completely unexpected errors', () => { }, }, commonBaseQueryApi, - {} + {}, ) expect(req).toBeInstanceOf(Promise) await expect(req).rejects.toBe(error) @@ -1109,14 +1109,14 @@ describe('timeout', () => { headers: headersToObject(request.headers), }) }, - { once: true } - ) + { once: true }, + ), ) const result = await baseQuery( { url: '/empty2', timeout: 200 }, commonBaseQueryApi, - {} + {}, ) expect(result?.error).toEqual({ diff --git a/packages/toolkit/src/query/tests/mocks/handlers.ts b/packages/toolkit/src/query/tests/mocks/handlers.ts index 17f707f743..3fe044fdf0 100644 --- a/packages/toolkit/src/query/tests/mocks/handlers.ts +++ b/packages/toolkit/src/query/tests/mocks/handlers.ts @@ -23,7 +23,7 @@ export const handlers = [ url: new URL(request.url), headers: headersToObject(request.headers), }) - } + }, ), http.post( @@ -49,25 +49,25 @@ export const handlers = [ url: new URL(request.url), headers: headersToObject(request.headers), }) - } + }, ), http.get('https://example.com/success', () => - HttpResponse.json({ value: 'success' }) + HttpResponse.json({ value: 'success' }), ), http.post('https://example.com/success', () => - HttpResponse.json({ value: 'success' }) + HttpResponse.json({ value: 'success' }), ), http.get('https://example.com/empty', () => new HttpResponse('')), http.get('https://example.com/error', () => - HttpResponse.json({ value: 'error' }, { status: 500 }) + HttpResponse.json({ value: 'error' }, { status: 500 }), ), http.post('https://example.com/error', () => - HttpResponse.json({ value: 'error' }, { status: 500 }) + HttpResponse.json({ value: 'error' }, { status: 500 }), ), http.get('https://example.com/nonstandard-error', () => @@ -76,16 +76,16 @@ export const handlers = [ success: false, message: 'This returns a 200 but is really an error', }, - { status: 200 } - ) + { status: 200 }, + ), ), http.get('https://example.com/mirror', ({ params }) => - HttpResponse.json(params) + HttpResponse.json(params), ), http.post('https://example.com/mirror', ({ params }) => - HttpResponse.json(params) + HttpResponse.json(params), ), http.get('https://example.com/posts/random', () => { @@ -96,6 +96,6 @@ export const handlers = [ http.get<{ id: string }, any, Pick>( 'https://example.com/post/:id', - ({ params }) => HttpResponse.json(posts[params.id]) + ({ params }) => HttpResponse.json(posts[params.id]), ), ] diff --git a/packages/toolkit/src/query/tests/optimisticUpdates.test.tsx b/packages/toolkit/src/query/tests/optimisticUpdates.test.tsx index afad253eb8..eb9893a3be 100644 --- a/packages/toolkit/src/query/tests/optimisticUpdates.test.tsx +++ b/packages/toolkit/src/query/tests/optimisticUpdates.test.tsx @@ -51,7 +51,7 @@ const api = createApi({ const { undo } = dispatch( api.util.updateQueryData('post', id, (draft) => { Object.assign(draft, patch) - }) + }), ) queryFulfilled.catch(undo) }, @@ -98,7 +98,7 @@ describe('basic lifecycle', () => { () => extendedApi.endpoints.test.useMutation(), { wrapper: storeRef.wrapper, - } + }, ) baseQuery.mockResolvedValue('success') @@ -121,7 +121,7 @@ describe('basic lifecycle', () => { () => extendedApi.endpoints.test.useMutation(), { wrapper: storeRef.wrapper, - } + }, ) baseQuery.mockRejectedValueOnce('error') @@ -172,7 +172,7 @@ describe('updateQueryData', () => { returnValue = storeRef.store.dispatch( api.util.updateQueryData('post', '3', (draft) => { draft.contents = 'I love cheese!' - }) + }), ) }) @@ -191,7 +191,7 @@ describe('updateQueryData', () => { act(() => { storeRef.store.dispatch( - api.util.patchQueryData('post', '3', returnValue.inversePatches) + api.util.patchQueryData('post', '3', returnValue.inversePatches), ) }) @@ -233,8 +233,8 @@ describe('updateQueryData', () => { contents: 'TODO', }) }, - true - ) + true, + ), ) }) @@ -292,8 +292,8 @@ describe('updateQueryData', () => { contents: 'TODO', }) }, - false - ) + false, + ), ) }) @@ -344,7 +344,7 @@ describe('updateQueryData', () => { returnValue = storeRef.store.dispatch( api.util.updateQueryData('post', '4', (draft) => { draft.contents = 'I love cheese!' - }) + }), ) }) @@ -384,7 +384,7 @@ describe('full integration', () => { }), { wrapper: storeRef.wrapper, - } + }, ) await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy()) @@ -409,7 +409,7 @@ describe('full integration', () => { id: '3', title: 'Meanwhile, this changed server-side.', contents: 'Delicious cheese!', - }) + }), ) }) @@ -435,7 +435,7 @@ describe('full integration', () => { }), { wrapper: storeRef.wrapper, - } + }, ) await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy()) @@ -462,7 +462,7 @@ describe('full integration', () => { id: '3', title: 'All about cheese.', contents: 'TODO', - }) + }), ) // mutation failed - will not invalidate query and not refetch data from the server @@ -474,8 +474,8 @@ describe('full integration', () => { title: 'Meanwhile, this changed server-side.', contents: 'TODO', }), - 50 - ) + 50, + ), ).rejects.toBeTruthy() act(() => void result.current.query.refetch()) @@ -488,7 +488,7 @@ describe('full integration', () => { title: 'Meanwhile, this changed server-side.', contents: 'TODO', }), - 50 + 50, ) }) }) diff --git a/packages/toolkit/src/query/tests/optimisticUpserts.test.tsx b/packages/toolkit/src/query/tests/optimisticUpserts.test.tsx index 8ff782620b..2902b84ccb 100644 --- a/packages/toolkit/src/query/tests/optimisticUpserts.test.tsx +++ b/packages/toolkit/src/query/tests/optimisticUpserts.test.tsx @@ -1,7 +1,11 @@ import { createApi } from '@reduxjs/toolkit/query/react' -import { actionsReducer, hookWaitFor, setupApiStore } from '../../tests/utils/helpers' +import { + actionsReducer, + hookWaitFor, + setupApiStore, +} from '../../tests/utils/helpers' import { renderHook, act, waitFor } from '@testing-library/react' -import { delay } from "msw" +import { delay } from 'msw' interface Post { id: string @@ -40,7 +44,7 @@ const api = createApi({ api.util.upsertQueryData('post', arg.id, { ...currentItem.data, ...arg, - }) + }), ) } }, @@ -101,7 +105,7 @@ describe('basic lifecycle', () => { title: 'Inserted title', } const insertPromise = storeRef.store.dispatch( - api.util.upsertQueryData('post', newPost.id, newPost) + api.util.upsertQueryData('post', newPost.id, newPost), ) await insertPromise @@ -118,7 +122,7 @@ describe('basic lifecycle', () => { } const updatePromise = storeRef.store.dispatch( - api.util.upsertQueryData('post', updatedPost.id, updatedPost) + api.util.upsertQueryData('post', updatedPost.id, updatedPost), ) await updatePromise @@ -134,7 +138,7 @@ describe('basic lifecycle', () => { () => extendedApi.endpoints.test.useMutation(), { wrapper: storeRef.wrapper, - } + }, ) baseQuery.mockResolvedValue('success') @@ -157,7 +161,7 @@ describe('basic lifecycle', () => { () => extendedApi.endpoints.test.useMutation(), { wrapper: storeRef.wrapper, - } + }, ) baseQuery.mockRejectedValueOnce('error') @@ -210,7 +214,7 @@ describe('upsertQueryData', () => { id: '3', title: 'All about cheese.', contents: 'I love cheese!', - }) + }), ) }) @@ -238,7 +242,7 @@ describe('upsertQueryData', () => { () => api.endpoints.post.useQuery('4'), { wrapper: storeRef.wrapper, - } + }, ) await hookWaitFor(() => expect(result.current.isError).toBeTruthy()) @@ -249,7 +253,7 @@ describe('upsertQueryData', () => { id: '4', title: 'All about cheese', contents: 'I love cheese!', - }) + }), ) }) @@ -282,7 +286,7 @@ describe('upsertQueryData', () => { const selector = api.endpoints.post.select('3') const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3')) const upsertRes = storeRef.store.dispatch( - api.util.upsertQueryData('post', '3', upsertedData) + api.util.upsertQueryData('post', '3', upsertedData), ) await upsertRes @@ -308,7 +312,7 @@ describe('upsertQueryData', () => { const selector = api.endpoints.post.select('3') const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3')) const upsertRes = storeRef.store.dispatch( - api.util.upsertQueryData('post', '3', upsertedData) + api.util.upsertQueryData('post', '3', upsertedData), ) await upsertRes @@ -349,7 +353,7 @@ describe('full integration', () => { }), { wrapper: storeRef.wrapper, - } + }, ) await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy()) @@ -377,7 +381,7 @@ describe('full integration', () => { id: '3', title: 'Meanwhile, this changed server-side.', contents: 'Delicious cheese!', - }) + }), ) }) @@ -403,7 +407,7 @@ describe('full integration', () => { }), { wrapper: storeRef.wrapper, - } + }, ) await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy()) @@ -436,8 +440,8 @@ describe('full integration', () => { title: 'Meanwhile, this changed server-side.', contents: 'TODO', }), - 50 - ) + 50, + ), ).rejects.toBeTruthy() act(() => void result.current.query.refetch()) @@ -450,14 +454,14 @@ describe('full integration', () => { title: 'Meanwhile, this changed server-side.', contents: 'TODO', }), - 50 + 50, ) }) test('Interop with in-flight requests', async () => { await act(async () => { const fetchRes = storeRef.store.dispatch( - api.endpoints.post2.initiate('3') + api.endpoints.post2.initiate('3'), ) const upsertRes = storeRef.store.dispatch( @@ -465,7 +469,7 @@ describe('full integration', () => { id: '3', title: 'Upserted title', contents: 'Upserted contents', - }) + }), ) const selectEntry = api.endpoints.post2.select('3') @@ -478,7 +482,7 @@ describe('full integration', () => { contents: 'Upserted contents', }) }, - { interval: 1, timeout: 15 } + { interval: 1, timeout: 15 }, ) await waitFor( () => { @@ -489,7 +493,7 @@ describe('full integration', () => { contents: 'TODO', }) }, - { interval: 1 } + { interval: 1 }, ) }) }) diff --git a/packages/toolkit/src/query/tests/polling.test.tsx b/packages/toolkit/src/query/tests/polling.test.tsx index bda59f4880..431b9ff1bb 100644 --- a/packages/toolkit/src/query/tests/polling.test.tsx +++ b/packages/toolkit/src/query/tests/polling.test.tsx @@ -27,7 +27,7 @@ let getSubscriptions: SubscriptionSelectors['getSubscriptions'] beforeEach(() => { ;({ getSubscriptions } = storeRef.store.dispatch( - api.internalActions.internal_getRTKQSubscriptions() + api.internalActions.internal_getRTKQSubscriptions(), ) as unknown as SubscriptionSelectors) }) @@ -42,7 +42,7 @@ describe('polling tests', () => { getPosts.initiate(1, { subscriptionOptions: { pollingInterval: 10 }, subscribe: true, - }) + }), ) expect(mockBaseQuery).toHaveBeenCalledTimes(1) @@ -60,7 +60,7 @@ describe('polling tests', () => { getPosts.initiate(1, { subscriptionOptions: { pollingInterval: 10 }, subscribe: true, - }) + }), ) const getSubs = createSubscriptionGetter(queryCacheKey) @@ -81,14 +81,14 @@ describe('polling tests', () => { getPosts.initiate(1, { subscriptionOptions: { pollingInterval: 10 }, subscribe: true, - }) + }), ) storeRef.store.dispatch( getPosts.initiate(1, { subscriptionOptions: { pollingInterval: 10 }, subscribe: true, - }) + }), ) await delay(10) @@ -108,14 +108,14 @@ describe('polling tests', () => { getPosts.initiate(1, { subscriptionOptions: { pollingInterval: 30000 }, subscribe: true, - }) + }), ) storeRef.store.dispatch( getPosts.initiate(1, { subscriptionOptions: { pollingInterval: 10 }, subscribe: true, - }) + }), ) await delay(20) @@ -132,7 +132,7 @@ describe('polling tests', () => { skipPollingIfUnfocused: true, }, subscribe: true, - }) + }), ) storeRef.store.dispatch(api.internalActions?.onFocusLost()) @@ -146,7 +146,7 @@ describe('polling tests', () => { skipPollingIfUnfocused: false, }, subscribe: true, - }) + }), ) storeRef.store.dispatch(api.internalActions?.onFocus()) @@ -168,7 +168,7 @@ describe('polling tests', () => { skipPollingIfUnfocused: false, }, subscribe: true, - }) + }), ) await delay(50) @@ -181,7 +181,7 @@ describe('polling tests', () => { skipPollingIfUnfocused: true, }, subscribe: true, - }) + }), ) storeRef.store.dispatch( @@ -191,7 +191,7 @@ describe('polling tests', () => { skipPollingIfUnfocused: false, }, subscribe: true, - }) + }), ) storeRef.store.dispatch(api.internalActions?.onFocusLost()) @@ -212,7 +212,7 @@ describe('polling tests', () => { skipPollingIfUnfocused: false, }, subscribe: true, - }) + }), ) const getSubs = createSubscriptionGetter(queryCacheKey) diff --git a/packages/toolkit/src/query/tests/refetchingBehaviors.test.tsx b/packages/toolkit/src/query/tests/refetchingBehaviors.test.tsx index 06b7fbccd9..be27d08d9f 100644 --- a/packages/toolkit/src/query/tests/refetchingBehaviors.test.tsx +++ b/packages/toolkit/src/query/tests/refetchingBehaviors.test.tsx @@ -62,13 +62,13 @@ describe('refetchOnFocus tests', () => { render(, { wrapper: storeRef.wrapper }) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('true') + expect(screen.getByTestId('isLoading').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) await act(async () => { @@ -78,7 +78,7 @@ describe('refetchOnFocus tests', () => { await delay(150) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('2') + expect(screen.getByTestId('amount').textContent).toBe('2'), ) }) @@ -102,13 +102,13 @@ describe('refetchOnFocus tests', () => { render(, { wrapper: storeRef.wrapper }) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('true') + expect(screen.getByTestId('isLoading').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) act(() => { @@ -118,7 +118,7 @@ describe('refetchOnFocus tests', () => { await delay(150) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) }) @@ -152,17 +152,17 @@ describe('refetchOnFocus tests', () => {

( - type: T + type: T, ): PayloadActionCreator // @public export function createAction< PA extends PrepareAction, - T extends string = string + T extends string = string, >( type: T, - prepareAction: PA + prepareAction: PA, ): PayloadActionCreator['payload'], T, PA> // @public (undocumented) export function createAsyncThunk( typePrefix: string, payloadCreator: AsyncThunkPayloadCreator, - options?: AsyncThunkOptions + options?: AsyncThunkOptions, ): AsyncThunk // @public (undocumented) export function createAsyncThunk< Returned, ThunkArg, - ThunkApiConfig extends AsyncThunkConfig + ThunkApiConfig extends AsyncThunkConfig, >( typePrefix: string, payloadCreator: AsyncThunkPayloadCreator, - options?: AsyncThunkOptions + options?: AsyncThunkOptions, ): AsyncThunk // @public @@ -287,7 +287,7 @@ export function createEntityAdapter(options?: { // @public export function createImmutableStateInvariantMiddleware( - options?: ImmutableStateInvariantMiddlewareOptions + options?: ImmutableStateInvariantMiddlewareOptions, ): Middleware export { createNextState } @@ -295,41 +295,41 @@ export { createNextState } // @public export function createReducer>( initialState: S | (() => S), - builderCallback: (builder: ActionReducerMapBuilder) => void + builderCallback: (builder: ActionReducerMapBuilder) => void, ): ReducerWithInitialState // @public export function createReducer< S extends NotFunction, - CR extends CaseReducers = CaseReducers + CR extends CaseReducers = CaseReducers, >( initialState: S | (() => S), actionsMap: CR, actionMatchers?: ActionMatcherDescriptionCollection, - defaultCaseReducer?: CaseReducer + defaultCaseReducer?: CaseReducer, ): ReducerWithInitialState export { createSelector } // @public export function createSerializableStateInvariantMiddleware( - options?: SerializableStateInvariantMiddlewareOptions + options?: SerializableStateInvariantMiddlewareOptions, ): Middleware // @public export function createSlice< State, CaseReducers extends SliceCaseReducers, - Name extends string = string + Name extends string = string, >( - options: CreateSliceOptions + options: CreateSliceOptions, ): Slice // @public export interface CreateSliceOptions< State = any, CR extends SliceCaseReducers = SliceCaseReducers, - Name extends string = string + Name extends string = string, > { extraReducers?: | CaseReducers, any> @@ -353,7 +353,7 @@ export { Draft } export interface EnhancedStore< S = any, A extends Action = UnknownAction, - M extends Middlewares = Middlewares + M extends Middlewares = Middlewares, > extends Store { dispatch: Dispatch & DispatchForMiddlewares } @@ -368,7 +368,7 @@ export interface EntityAdapter extends EntityStateAdapter { getSelectors(): EntitySelectors> // (undocumented) getSelectors( - selectState: (state: V) => EntityState + selectState: (state: V) => EntityState, ): EntitySelectors // (undocumented) selectId: IdSelector @@ -406,102 +406,102 @@ export interface EntityStateAdapter { // (undocumented) addMany>( state: PreventAny, - entities: readonly T[] | Record + entities: readonly T[] | Record, ): S // (undocumented) addMany>( state: PreventAny, - entities: PayloadAction> + entities: PayloadAction>, ): S // (undocumented) addOne>(state: PreventAny, entity: T): S // (undocumented) addOne>( state: PreventAny, - action: PayloadAction + action: PayloadAction, ): S // (undocumented) removeAll>(state: PreventAny): S // (undocumented) removeMany>( state: PreventAny, - keys: readonly EntityId[] + keys: readonly EntityId[], ): S // (undocumented) removeMany>( state: PreventAny, - keys: PayloadAction + keys: PayloadAction, ): S // (undocumented) removeOne>(state: PreventAny, key: EntityId): S // (undocumented) removeOne>( state: PreventAny, - key: PayloadAction + key: PayloadAction, ): S // (undocumented) setAll>( state: PreventAny, - entities: readonly T[] | Record + entities: readonly T[] | Record, ): S // (undocumented) setAll>( state: PreventAny, - entities: PayloadAction> + entities: PayloadAction>, ): S // (undocumented) setMany>( state: PreventAny, - entities: readonly T[] | Record + entities: readonly T[] | Record, ): S // (undocumented) setMany>( state: PreventAny, - entities: PayloadAction> + entities: PayloadAction>, ): S // (undocumented) setOne>(state: PreventAny, entity: T): S // (undocumented) setOne>( state: PreventAny, - action: PayloadAction + action: PayloadAction, ): S // (undocumented) updateMany>( state: PreventAny, - updates: ReadonlyArray> + updates: ReadonlyArray>, ): S // (undocumented) updateMany>( state: PreventAny, - updates: PayloadAction>> + updates: PayloadAction>>, ): S // (undocumented) updateOne>( state: PreventAny, - update: Update + update: Update, ): S // (undocumented) updateOne>( state: PreventAny, - update: PayloadAction> + update: PayloadAction>, ): S // (undocumented) upsertMany>( state: PreventAny, - entities: readonly T[] | Record + entities: readonly T[] | Record, ): S // (undocumented) upsertMany>( state: PreventAny, - entities: PayloadAction> + entities: PayloadAction>, ): S // (undocumented) upsertOne>(state: PreventAny, entity: T): S // (undocumented) upsertOne>( state: PreventAny, - entity: PayloadAction + entity: PayloadAction, ): S } @@ -511,7 +511,7 @@ export function findNonSerializableValue( path?: string, isSerializable?: (value: unknown) => boolean, getEntries?: (value: unknown) => [string, any][], - ignoredPaths?: readonly (string | RegExp)[] + ignoredPaths?: readonly (string | RegExp)[], ): NonSerializableValue | false export { freeze } @@ -523,12 +523,12 @@ export function getDefaultMiddleware< thunk: true immutableCheck: true serializableCheck: true - } + }, >(options?: O): MiddlewareArray | ThunkMiddlewareFor> // @public export function getType( - actionCreator: PayloadActionCreator + actionCreator: PayloadActionCreator, ): T // @public (undocumented) @@ -547,7 +547,7 @@ export interface ImmutableStateInvariantMiddlewareOptions { export function isAllOf, ...Matcher[]]>( ...matchers: Matchers ): ( - action: any + action: any, ) => action is UnionToIntersection> // @public @@ -557,38 +557,38 @@ export function isAnyOf, ...Matcher[]]>( // @public export function isAsyncThunkAction(): ( - action: any + action: any, ) => action is UnknownAsyncThunkAction // @public export function isAsyncThunkAction< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): (action: any) => action is ActionsFromAsyncThunk // @public export function isAsyncThunkAction( - action: any + action: any, ): action is UnknownAsyncThunkAction export { isDraft } // @public export function isFulfilled(): ( - action: any + action: any, ) => action is UnknownAsyncThunkFulfilledAction // @public export function isFulfilled< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): (action: any) => action is FulfilledActionFromAsyncThunk // @public export function isFulfilled( - action: any + action: any, ): action is UnknownAsyncThunkFulfilledAction // @public @@ -596,12 +596,12 @@ export function isImmutableDefault(value: unknown): boolean // @public export function isPending(): ( - action: any + action: any, ) => action is UnknownAsyncThunkPendingAction // @public export function isPending< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): (action: any) => action is PendingActionFromAsyncThunk @@ -617,43 +617,43 @@ export function isPlainObject(value: unknown): value is object // @public export function isRejected(): ( - action: any + action: any, ) => action is UnknownAsyncThunkRejectedAction // @public export function isRejected< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): (action: any) => action is RejectedActionFromAsyncThunk // @public export function isRejected( - action: any + action: any, ): action is UnknownAsyncThunkRejectedAction // @public export function isRejectedWithValue(): ( - action: any + action: any, ) => action is UnknownAsyncThunkRejectedAction // @public export function isRejectedWithValue< - AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]] + AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]], >( ...asyncThunks: AsyncThunks ): ( - action: any + action: any, ) => action is RejectedWithValueActionFromAsyncThunk // @public export function isRejectedWithValue( - action: any + action: any, ): action is UnknownAsyncThunkRejectedAction // @public (undocumented) export class MiddlewareArray< - Middlewares extends Middleware + Middlewares extends Middleware, > extends Array { // (undocumented) static get [Symbol.species](): any @@ -661,7 +661,7 @@ export class MiddlewareArray< constructor(...items: Middlewares[]) // (undocumented) concat>>( - items: AdditionalMiddlewares + items: AdditionalMiddlewares, ): MiddlewareArray // (undocumented) concat>>( @@ -669,7 +669,7 @@ export class MiddlewareArray< ): MiddlewareArray // (undocumented) prepend>>( - items: AdditionalMiddlewares + items: AdditionalMiddlewares, ): MiddlewareArray // (undocumented) prepend>>( @@ -696,7 +696,7 @@ export type PayloadAction< P = void, T extends string = string, M = never, - E = never + E = never, > = { payload: P type: T @@ -715,7 +715,7 @@ export type PayloadAction< export type PayloadActionCreator< P = void, T extends string = string, - PA extends PrepareAction

, - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('true') + expect(screen.getByTestId('isLoading').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) act(() => { @@ -170,13 +170,13 @@ describe('refetchOnFocus tests', () => { }) expect(screen.getByTestId('isLoading').textContent).toBe('false') await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('true') + expect(screen.getByTestId('isFetching').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('false') + expect(screen.getByTestId('isFetching').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('2') + expect(screen.getByTestId('amount').textContent).toBe('2'), ) }) @@ -200,13 +200,13 @@ describe('refetchOnFocus tests', () => { const { unmount } = render(, { wrapper: storeRef.wrapper }) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('true') + expect(screen.getByTestId('isLoading').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) unmount() @@ -241,13 +241,13 @@ describe('refetchOnReconnect tests', () => { render(, { wrapper: storeRef.wrapper }) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('true') + expect(screen.getByTestId('isLoading').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) act(() => { @@ -256,13 +256,13 @@ describe('refetchOnReconnect tests', () => { }) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('true') + expect(screen.getByTestId('isFetching').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('false') + expect(screen.getByTestId('isFetching').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('2') + expect(screen.getByTestId('amount').textContent).toBe('2'), ) }) @@ -286,13 +286,13 @@ describe('refetchOnReconnect tests', () => { render(, { wrapper: storeRef.wrapper }) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('true') + expect(screen.getByTestId('isLoading').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) act(() => { @@ -301,7 +301,7 @@ describe('refetchOnReconnect tests', () => { }) expect(screen.getByTestId('isFetching').textContent).toBe('false') await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) }) @@ -335,17 +335,17 @@ describe('refetchOnReconnect tests', () => {
, - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('true') + expect(screen.getByTestId('isLoading').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) act(() => { @@ -354,13 +354,13 @@ describe('refetchOnReconnect tests', () => { }) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('true') + expect(screen.getByTestId('isFetching').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('false') + expect(screen.getByTestId('isFetching').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('2') + expect(screen.getByTestId('amount').textContent).toBe('2'), ) }) }) @@ -389,7 +389,7 @@ describe('customListenersHandler', () => { window.removeEventListener('online', handleOnline) console.log('cleanup!') } - } + }, ) await delay(150) @@ -415,13 +415,13 @@ describe('customListenersHandler', () => { expect(consoleSpy).toHaveBeenCalledWith('setup!') await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('true') + expect(screen.getByTestId('isLoading').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isLoading').textContent).toBe('false') + expect(screen.getByTestId('isLoading').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('1') + expect(screen.getByTestId('amount').textContent).toBe('1'), ) act(() => { @@ -439,18 +439,18 @@ describe('customListenersHandler', () => { expect( defaultApi.internalActions.onOnline.match( - mockCallsWithoutInternals[1][0] as any - ) + mockCallsWithoutInternals[1][0] as any, + ), ).toBe(true) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('true') + expect(screen.getByTestId('isFetching').textContent).toBe('true'), ) await waitFor(() => - expect(screen.getByTestId('isFetching').textContent).toBe('false') + expect(screen.getByTestId('isFetching').textContent).toBe('false'), ) await waitFor(() => - expect(screen.getByTestId('amount').textContent).toBe('2') + expect(screen.getByTestId('amount').textContent).toBe('2'), ) unsubscribe() diff --git a/packages/toolkit/src/query/tests/retry.test.ts b/packages/toolkit/src/query/tests/retry.test.ts index de71e1f644..dcc3ac8415 100644 --- a/packages/toolkit/src/query/tests/retry.test.ts +++ b/packages/toolkit/src/query/tests/retry.test.ts @@ -317,7 +317,7 @@ describe('configuration', () => { const attempts = Math.min(attempt, maxRetries) const timeout = attempts * 300 // Scale up by 300ms per request, ex: 300ms, 600ms, 900ms, 1200ms... await new Promise((resolve) => - setTimeout((res: any) => resolve(res), timeout) + setTimeout((res: any) => resolve(res), timeout), ) }, }) diff --git a/packages/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx b/packages/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx index 3a7609fb80..5ab0d8f215 100644 --- a/packages/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx +++ b/packages/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx @@ -57,7 +57,7 @@ describe('fixedCacheKey', () => { , - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') @@ -69,7 +69,7 @@ describe('fixedCacheKey', () => { }) await waitFor(() => - expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') + expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'), ) expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') @@ -81,7 +81,7 @@ describe('fixedCacheKey', () => { , - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') @@ -119,7 +119,7 @@ describe('fixedCacheKey', () => { , - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') @@ -137,7 +137,7 @@ describe('fixedCacheKey', () => { }) await waitFor(() => - expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') + expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'), ) // the components with the first cache key should be affected @@ -159,7 +159,7 @@ describe('fixedCacheKey', () => { }) await waitFor(() => - expect(getByTestId(c3, 'status').textContent).toBe('fulfilled') + expect(getByTestId(c3, 'status').textContent).toBe('fulfilled'), ) // the components with the first cache key should be unaffected @@ -203,7 +203,7 @@ describe('fixedCacheKey', () => { , - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') @@ -215,7 +215,7 @@ describe('fixedCacheKey', () => { }) await waitFor(() => - expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') + expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'), ) expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') @@ -233,7 +233,7 @@ describe('fixedCacheKey', () => { }) await waitFor(() => - expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') + expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'), ) expect(getByTestId(c1, 'data').textContent).toBe('C1') @@ -252,7 +252,7 @@ describe('fixedCacheKey', () => { , - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') @@ -264,7 +264,7 @@ describe('fixedCacheKey', () => { }) await waitFor(() => - expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') + expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'), ) expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('fulfilled') @@ -315,7 +315,7 @@ describe('fixedCacheKey', () => { , - { wrapper: storeRef.wrapper } + { wrapper: storeRef.wrapper }, ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') diff --git a/packages/toolkit/src/query/tests/utils.test.ts b/packages/toolkit/src/query/tests/utils.test.ts index 1124f0294b..859865c6d7 100644 --- a/packages/toolkit/src/query/tests/utils.test.ts +++ b/packages/toolkit/src/query/tests/utils.test.ts @@ -13,7 +13,7 @@ afterAll(() => { describe('isOnline', () => { test('Assumes online=true in a node env', () => { vi.spyOn(window, 'navigator', 'get').mockImplementation( - () => undefined as any + () => undefined as any, ) expect(navigator).toBeUndefined() @@ -22,14 +22,14 @@ describe('isOnline', () => { test('Returns false if navigator isOnline=false', () => { vi.spyOn(window, 'navigator', 'get').mockImplementation( - () => ({ onLine: false } as any) + () => ({ onLine: false }) as any, ) expect(isOnline()).toBe(false) }) test('Returns true if navigator isOnline=true', () => { vi.spyOn(window, 'navigator', 'get').mockImplementation( - () => ({ onLine: true } as any) + () => ({ onLine: true }) as any, ) expect(isOnline()).toBe(true) }) @@ -38,7 +38,7 @@ describe('isOnline', () => { describe('isDocumentVisible', () => { test('Assumes true when in a non-browser env', () => { vi.spyOn(window, 'document', 'get').mockImplementation( - () => undefined as any + () => undefined as any, ) expect(window.document).toBeUndefined() expect(isDocumentVisible()).toBe(true) @@ -46,28 +46,28 @@ describe('isDocumentVisible', () => { test('Returns false when hidden=true', () => { vi.spyOn(window, 'document', 'get').mockImplementation( - () => ({ visibilityState: 'hidden' } as any) + () => ({ visibilityState: 'hidden' }) as any, ) expect(isDocumentVisible()).toBe(false) }) test('Returns true when visibilityState=prerender', () => { vi.spyOn(window, 'document', 'get').mockImplementation( - () => ({ visibilityState: 'prerender' } as any) + () => ({ visibilityState: 'prerender' }) as any, ) expect(document.visibilityState).toBe('prerender') expect(isDocumentVisible()).toBe(true) }) test('Returns true when visibilityState=visible', () => { vi.spyOn(window, 'document', 'get').mockImplementation( - () => ({ visibilityState: 'visible' } as any) + () => ({ visibilityState: 'visible' }) as any, ) expect(document.visibilityState).toBe('visible') expect(isDocumentVisible()).toBe(true) }) test('Returns true when visibilityState=undefined', () => { vi.spyOn(window, 'document', 'get').mockImplementation( - () => ({ visibilityState: undefined } as any) + () => ({ visibilityState: undefined }) as any, ) expect(document.visibilityState).toBeUndefined() expect(isDocumentVisible()).toBe(true) diff --git a/packages/toolkit/src/query/tsHelpers.ts b/packages/toolkit/src/query/tsHelpers.ts index 7c2734b448..f663e9965b 100644 --- a/packages/toolkit/src/query/tsHelpers.ts +++ b/packages/toolkit/src/query/tsHelpers.ts @@ -24,9 +24,8 @@ export type NonOptionalKeys = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T] -export type HasRequiredProps = NonOptionalKeys extends never - ? False - : True +export type HasRequiredProps = + NonOptionalKeys extends never ? False : True export type OptionalIfAllPropsOptional = HasRequiredProps diff --git a/packages/toolkit/src/query/utils/isOnline.ts b/packages/toolkit/src/query/utils/isOnline.ts index af34850c9b..0dcb65b97a 100644 --- a/packages/toolkit/src/query/utils/isOnline.ts +++ b/packages/toolkit/src/query/utils/isOnline.ts @@ -7,6 +7,6 @@ export function isOnline() { return typeof navigator === 'undefined' ? true : navigator.onLine === undefined - ? true - : navigator.onLine + ? true + : navigator.onLine } diff --git a/packages/toolkit/src/query/utils/joinUrls.ts b/packages/toolkit/src/query/utils/joinUrls.ts index afcf1ad2e1..31e5e24953 100644 --- a/packages/toolkit/src/query/utils/joinUrls.ts +++ b/packages/toolkit/src/query/utils/joinUrls.ts @@ -5,7 +5,7 @@ const withoutLeadingSlash = (url: string) => url.replace(/^\//, '') export function joinUrls( base: string | undefined, - url: string | undefined + url: string | undefined, ): string { if (!base) { return url! diff --git a/packages/toolkit/src/serializableStateInvariantMiddleware.ts b/packages/toolkit/src/serializableStateInvariantMiddleware.ts index 118d3f50ec..a4dba23562 100644 --- a/packages/toolkit/src/serializableStateInvariantMiddleware.ts +++ b/packages/toolkit/src/serializableStateInvariantMiddleware.ts @@ -39,7 +39,7 @@ export function findNonSerializableValue( isSerializable: (value: unknown) => boolean = isPlain, getEntries?: (value: unknown) => [string, any][], ignoredPaths: IgnorePaths = [], - cache?: WeakSet + cache?: WeakSet, ): NonSerializableValue | false { let foundNestedSerializable: NonSerializableValue | false @@ -89,7 +89,7 @@ export function findNonSerializableValue( isSerializable, getEntries, ignoredPaths, - cache + cache, ) if (foundNestedSerializable) { @@ -186,7 +186,7 @@ export interface SerializableStateInvariantMiddlewareOptions { * @public */ export function createSerializableStateInvariantMiddleware( - options: SerializableStateInvariantMiddlewareOptions = {} + options: SerializableStateInvariantMiddlewareOptions = {}, ): Middleware { if (process.env.NODE_ENV === 'production') { return () => (next) => (action) => next(action) @@ -215,7 +215,7 @@ export function createSerializableStateInvariantMiddleware( const measureUtils = getTimeMeasureUtils( warnAfter, - 'SerializableStateInvariantMiddleware' + 'SerializableStateInvariantMiddleware', ) if ( @@ -232,7 +232,7 @@ export function createSerializableStateInvariantMiddleware( isSerializable, getEntries, ignoredActionPaths, - cache + cache, ) if (foundActionNonSerializableValue) { @@ -244,7 +244,7 @@ export function createSerializableStateInvariantMiddleware( '\nTake a look at the logic that dispatched this action: ', action, '\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)', - '\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)' + '\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)', ) } }) @@ -260,7 +260,7 @@ export function createSerializableStateInvariantMiddleware( isSerializable, getEntries, ignoredPaths, - cache + cache, ) if (foundStateNonSerializableValue) { @@ -271,7 +271,7 @@ export function createSerializableStateInvariantMiddleware( value, ` Take a look at the reducer(s) handling this action type: ${action.type}. -(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)` +(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`, ) } }) diff --git a/packages/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts b/packages/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts index 65f83ee063..25d5df9568 100644 --- a/packages/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts +++ b/packages/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts @@ -19,7 +19,7 @@ describe('createActionCreatorInvariantMiddleware', () => { it('sends the action through the middleware chain', () => { const next = vi.fn() const dispatch = createActionCreatorInvariantMiddleware()( - {} as MiddlewareAPI + {} as MiddlewareAPI, )(next) dispatch({ type: 'SOME_ACTION' }) @@ -29,10 +29,10 @@ describe('createActionCreatorInvariantMiddleware', () => { }) const makeActionTester = ( - options?: ActionCreatorInvariantMiddlewareOptions + options?: ActionCreatorInvariantMiddlewareOptions, ) => createActionCreatorInvariantMiddleware(options)({} as MiddlewareAPI)( - (action) => action + (action) => action, ) it('logs a warning to console if an action creator is mistakenly dispatched', () => { diff --git a/packages/toolkit/src/tests/combinedTest.test.ts b/packages/toolkit/src/tests/combinedTest.test.ts index 7f906d8182..a130df7a1d 100644 --- a/packages/toolkit/src/tests/combinedTest.test.ts +++ b/packages/toolkit/src/tests/combinedTest.test.ts @@ -48,7 +48,7 @@ describe('Combined entity slice', () => { async (arg, { getState, dispatch, extra, requestId, signal }) => { const state = getState() return fakeBooks - } + }, ) const booksSlice = createSlice({ diff --git a/packages/toolkit/src/tests/configureStore.test.ts b/packages/toolkit/src/tests/configureStore.test.ts index 19ad7ee371..3d78068919 100644 --- a/packages/toolkit/src/tests/configureStore.test.ts +++ b/packages/toolkit/src/tests/configureStore.test.ts @@ -36,7 +36,7 @@ describe('configureStore', async () => { expect(redux.createStore).toHaveBeenCalledWith( reducer, undefined, - expect.any(Function) + expect.any(Function), ) expect(redux.applyMiddleware).toHaveBeenCalled() expect(composeWithDevToolsSpy).toHaveBeenCalled() // @remap-prod-remove-line @@ -57,7 +57,7 @@ describe('configureStore', async () => { expect(redux.createStore).toHaveBeenCalledWith( expect.any(Function), undefined, - expect.any(Function) + expect.any(Function), ) }) }) @@ -65,7 +65,7 @@ describe('configureStore', async () => { describe('given no reducer', () => { it('throws', () => { expect(configureStore).toThrow( - '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers' + '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers', ) }) }) @@ -73,14 +73,14 @@ describe('configureStore', async () => { describe('given no middleware', () => { it('calls createStore without any middleware', () => { expect( - configureStore({ middleware: () => new Tuple(), reducer }) + configureStore({ middleware: () => new Tuple(), reducer }), ).toBeInstanceOf(Object) expect(redux.applyMiddleware).toHaveBeenCalledWith() expect(composeWithDevToolsSpy).toHaveBeenCalled() // @remap-prod-remove-line expect(redux.createStore).toHaveBeenCalledWith( reducer, undefined, - expect.any(Function) + expect.any(Function), ) }) }) @@ -89,7 +89,7 @@ describe('configureStore', async () => { it('throws an error requiring a callback', () => { // @ts-expect-error expect(() => configureStore({ middleware: [], reducer })).toThrow( - '`middleware` field must be a callback' + '`middleware` field must be a callback', ) }) }) @@ -97,19 +97,19 @@ describe('configureStore', async () => { describe('given undefined middleware', () => { it('calls createStore with default middleware', () => { expect(configureStore({ middleware: undefined, reducer })).toBeInstanceOf( - Object + Object, ) expect(redux.applyMiddleware).toHaveBeenCalledWith( expect.any(Function), // immutableCheck expect.any(Function), // thunk expect.any(Function), // serializableCheck - expect.any(Function) // actionCreatorCheck + expect.any(Function), // actionCreatorCheck ) expect(composeWithDevToolsSpy).toHaveBeenCalled() // @remap-prod-remove-line expect(redux.createStore).toHaveBeenCalledWith( reducer, undefined, - expect.any(Function) + expect.any(Function), ) }) }) @@ -118,9 +118,9 @@ describe('configureStore', async () => { it('throws an error', () => { const invalidBuilder = vi.fn((getDefaultMiddleware) => undefined as any) expect(() => - configureStore({ middleware: invalidBuilder, reducer }) + configureStore({ middleware: invalidBuilder, reducer }), ).toThrow( - 'when using a middleware builder function, an array of middleware must be returned' + 'when using a middleware builder function, an array of middleware must be returned', ) }) }) @@ -129,7 +129,7 @@ describe('configureStore', async () => { it('throws an error', () => { const invalidBuilder = vi.fn((getDefaultMiddleware) => [true] as any) expect(() => - configureStore({ middleware: invalidBuilder, reducer }) + configureStore({ middleware: invalidBuilder, reducer }), ).toThrow('each middleware provided to configureStore must be a function') }) }) @@ -139,14 +139,14 @@ describe('configureStore', async () => { const thank: Redux.Middleware = (_store) => (next) => (action) => next(action) expect( - configureStore({ middleware: () => new Tuple(thank), reducer }) + configureStore({ middleware: () => new Tuple(thank), reducer }), ).toBeInstanceOf(Object) expect(redux.applyMiddleware).toHaveBeenCalledWith(thank) expect(composeWithDevToolsSpy).toHaveBeenCalled() // @remap-prod-remove-line expect(redux.createStore).toHaveBeenCalledWith( reducer, undefined, - expect.any(Function) + expect.any(Function), ) }) }) @@ -154,7 +154,7 @@ describe('configureStore', async () => { describe('middleware builder notation', () => { it('calls builder, passes getDefaultMiddleware and uses returned middlewares', () => { const thank = vi.fn( - ((_store) => (next) => (action) => 'foobar') as Redux.Middleware + ((_store) => (next) => (action) => 'foobar') as Redux.Middleware, ) const builder = vi.fn((getDefaultMiddleware) => { @@ -175,14 +175,14 @@ describe('configureStore', async () => { describe('with devTools disabled', () => { it('calls createStore without devTools enhancer', () => { expect(configureStore({ devTools: false, reducer })).toBeInstanceOf( - Object + Object, ) expect(redux.applyMiddleware).toHaveBeenCalled() expect(redux.compose).toHaveBeenCalled() expect(redux.createStore).toHaveBeenCalledWith( reducer, undefined, - expect.any(Function) + expect.any(Function), ) }) }) @@ -194,14 +194,14 @@ describe('configureStore', async () => { trace: true, } expect(configureStore({ devTools: options, reducer })).toBeInstanceOf( - Object + Object, ) expect(redux.applyMiddleware).toHaveBeenCalled() expect(composeWithDevToolsSpy).toHaveBeenCalledWith(options) // @remap-prod-remove-line expect(redux.createStore).toHaveBeenCalledWith( reducer, undefined, - expect.any(Function) + expect.any(Function), ) }) }) @@ -214,7 +214,7 @@ describe('configureStore', async () => { expect(redux.createStore).toHaveBeenCalledWith( reducer, undefined, - expect.any(Function) + expect.any(Function), ) }) }) @@ -238,14 +238,14 @@ describe('configureStore', async () => { configureStore({ enhancers: (gDE) => gDE().concat(dummyEnhancer), reducer, - }) + }), ).toBeInstanceOf(Object) expect(redux.applyMiddleware).toHaveBeenCalled() expect(composeWithDevToolsSpy).toHaveBeenCalled() // @remap-prod-remove-line expect(redux.createStore).toHaveBeenCalledWith( reducer, undefined, - expect.any(Function) + expect.any(Function), ) expect(dummyEnhancerCalled).toBe(true) @@ -254,19 +254,19 @@ describe('configureStore', async () => { describe('invalid arguments', () => { test('enhancers is not a callback', () => { expect(() => configureStore({ reducer, enhancers: [] as any })).toThrow( - '`enhancers` field must be a callback' + '`enhancers` field must be a callback', ) }) test('callback fails to return array', () => { expect(() => - configureStore({ reducer, enhancers: (() => {}) as any }) + configureStore({ reducer, enhancers: (() => {}) as any }), ).toThrow('`enhancers` callback must return an array') }) test('array contains non-function', () => { expect(() => - configureStore({ reducer, enhancers: (() => ['']) as any }) + configureStore({ reducer, enhancers: (() => ['']) as any }), ).toThrow('each enhancer provided to configureStore must be a function') }) }) @@ -288,7 +288,7 @@ describe('configureStore', async () => { expect(dummyEnhancerCalled).toBe(true) expect(consoleSpy).toHaveBeenCalledWith( - 'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`' + 'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`', ) }) it("doesn't warn when middleware enhancer is excluded if no middlewares provided", () => { diff --git a/packages/toolkit/src/tests/createAction.test.ts b/packages/toolkit/src/tests/createAction.test.ts index 2c4a80e13d..74e02e17cd 100644 --- a/packages/toolkit/src/tests/createAction.test.ts +++ b/packages/toolkit/src/tests/createAction.test.ts @@ -98,7 +98,7 @@ describe('createAction', () => { 'A_TYPE', (a: string, b: string, c: string) => ({ payload: a + b + c, - }) + }), ) expect(actionCreator('1', '2', '3').payload).toBe('123') }) diff --git a/packages/toolkit/src/tests/createAsyncThunk.test.ts b/packages/toolkit/src/tests/createAsyncThunk.test.ts index cf39d269a9..ef6ae71838 100644 --- a/packages/toolkit/src/tests/createAsyncThunk.test.ts +++ b/packages/toolkit/src/tests/createAsyncThunk.test.ts @@ -4,7 +4,7 @@ import { createAsyncThunk, createReducer, unwrapResult, - miniSerializeError + miniSerializeError, } from '@reduxjs/toolkit' import { vi } from 'vitest' @@ -40,13 +40,13 @@ describe('createAsyncThunk', () => { const thunkActionCreator = createAsyncThunk('testType', async () => 42) expect(thunkActionCreator.settled).toEqual(expect.any(Function)) expect(thunkActionCreator.settled(thunkActionCreator.pending(''))).toBe( - false + false, ) expect( - thunkActionCreator.settled(thunkActionCreator.rejected(null, '')) + thunkActionCreator.settled(thunkActionCreator.rejected(null, '')), ).toBe(true) expect( - thunkActionCreator.settled(thunkActionCreator.fulfilled(42, '')) + thunkActionCreator.settled(thunkActionCreator.fulfilled(42, '')), ).toBe(true) }) @@ -86,7 +86,7 @@ describe('createAsyncThunk', () => { passedArg = arg generatedRequestId = requestId return result - } + }, ) const thunkFunction = thunkActionCreator(args) @@ -102,12 +102,12 @@ describe('createAsyncThunk', () => { expect(dispatch).toHaveBeenNthCalledWith( 1, - thunkActionCreator.pending(generatedRequestId, args) + thunkActionCreator.pending(generatedRequestId, args), ) expect(dispatch).toHaveBeenNthCalledWith( 2, - thunkActionCreator.fulfilled(result, generatedRequestId, args) + thunkActionCreator.fulfilled(result, generatedRequestId, args), ) }) @@ -124,7 +124,7 @@ describe('createAsyncThunk', () => { async (args: number, { requestId }) => { generatedRequestId = requestId throw error - } + }, ) const thunkFunction = thunkActionCreator(args) @@ -135,7 +135,7 @@ describe('createAsyncThunk', () => { expect(dispatch).toHaveBeenNthCalledWith( 1, - thunkActionCreator.pending(generatedRequestId, args) + thunkActionCreator.pending(generatedRequestId, args), ) expect(dispatch).toHaveBeenCalledTimes(2) @@ -160,7 +160,7 @@ describe('createAsyncThunk', () => { async (args: number, { requestId }) => { generatedRequestId = requestId throw errorObject - } + }, ) const thunkFunction = thunkActionCreator(args) @@ -171,7 +171,7 @@ describe('createAsyncThunk', () => { expect(dispatch).toHaveBeenNthCalledWith( 1, - thunkActionCreator.pending(generatedRequestId, args) + thunkActionCreator.pending(generatedRequestId, args), ) expect(dispatch).toHaveBeenCalledTimes(2) @@ -199,7 +199,7 @@ describe('createAsyncThunk', () => { async (args: number, { requestId }) => { generatedRequestId = requestId throw errorObject - } + }, ) const thunkFunction = thunkActionCreator(args) @@ -210,7 +210,7 @@ describe('createAsyncThunk', () => { expect(dispatch).toHaveBeenNthCalledWith( 1, - thunkActionCreator.pending(generatedRequestId, args) + thunkActionCreator.pending(generatedRequestId, args), ) expect(dispatch).toHaveBeenCalledTimes(2) @@ -244,7 +244,7 @@ describe('createAsyncThunk', () => { generatedRequestId = requestId return rejectWithValue(errorPayload) - } + }, ) const thunkFunction = thunkActionCreator(args) @@ -255,7 +255,7 @@ describe('createAsyncThunk', () => { expect(dispatch).toHaveBeenNthCalledWith( 1, - thunkActionCreator.pending(generatedRequestId, args) + thunkActionCreator.pending(generatedRequestId, args), ) expect(dispatch).toHaveBeenCalledTimes(2) @@ -289,7 +289,7 @@ describe('createAsyncThunk', () => { generatedRequestId = requestId throw rejectWithValue(errorPayload) - } + }, ) const thunkFunction = thunkActionCreator(args) @@ -300,7 +300,7 @@ describe('createAsyncThunk', () => { expect(dispatch).toHaveBeenNthCalledWith( 1, - thunkActionCreator.pending(generatedRequestId, args) + thunkActionCreator.pending(generatedRequestId, args), ) expect(dispatch).toHaveBeenCalledTimes(2) @@ -343,7 +343,7 @@ describe('createAsyncThunk', () => { } return rejectWithValue(errorPayload) } - } + }, ) const thunkFunction = thunkActionCreator(args) @@ -354,7 +354,7 @@ describe('createAsyncThunk', () => { expect(dispatch).toHaveBeenNthCalledWith( 1, - thunkActionCreator.pending(generatedRequestId, args) + thunkActionCreator.pending(generatedRequestId, args), ) expect(dispatch).toHaveBeenCalledTimes(2) @@ -377,8 +377,8 @@ describe('createAsyncThunk with abortController', () => { reject( new DOMException( 'This should never be reached as it should already be handled.', - 'AbortError' - ) + 'AbortError', + ), ) } signal.addEventListener('abort', () => { @@ -386,7 +386,7 @@ describe('createAsyncThunk with abortController', () => { }) setTimeout(resolve, 100) }) - } + }, ) let store = configureStore({ @@ -437,7 +437,7 @@ describe('createAsyncThunk with abortController', () => { // calling unwrapResult on the returned object re-throws the error from the abortablePayloadCreator expect(() => unwrapResult(result)).toThrowError( - expect.objectContaining(expectedAbortedAction.error) + expect.objectContaining(expectedAbortedAction.error), ) }) @@ -471,7 +471,7 @@ describe('createAsyncThunk with abortController', () => { // calling unwrapResult on the returned object re-throws the error from the abortablePayloadCreator expect(() => unwrapResult(result)).toThrowError( - expect.objectContaining(expectedAbortedAction.error) + expect.objectContaining(expectedAbortedAction.error), ) }) @@ -496,7 +496,7 @@ describe('createAsyncThunk with abortController', () => { }) describe('behaviour with missing AbortController', () => { - let keepAbortController: typeof window['AbortController'] + let keepAbortController: (typeof window)['AbortController'] let freshlyLoadedModule: typeof import('../createAsyncThunk') let restore: () => void = () => {} let nodeEnv: string @@ -523,7 +523,7 @@ describe('createAsyncThunk with abortController', () => { 'longRunning', async () => { await new Promise((resolve) => setTimeout(resolve, 30000)) - } + }, ) expect(longRunningAsyncThunk()).toThrow('AbortController is not defined') @@ -599,7 +599,7 @@ describe('conditional skipping of asyncThunks', () => { expect(condition).toHaveBeenCalledTimes(1) expect(condition).toHaveBeenLastCalledWith( arg, - expect.objectContaining({ getState, extra }) + expect.objectContaining({ getState, extra }), ) }) @@ -625,7 +625,7 @@ describe('conditional skipping of asyncThunks', () => { await asyncThunk(arg)(dispatch, getState, extra) expect(dispatch).toHaveBeenCalledTimes(1) expect(dispatch).toHaveBeenLastCalledWith( - expect.objectContaining({ type: 'test/rejected' }) + expect.objectContaining({ type: 'test/rejected' }), ) }) @@ -662,7 +662,7 @@ describe('conditional skipping of asyncThunks', () => { }) const promise = asyncThunk(arg)(dispatch, getState, extra) promise.abort( - `If the promise was 1. somehow canceled, 2. in a 'started' state and 3. we attempted to abort, this would crash the tests` + `If the promise was 1. somehow canceled, 2. in a 'started' state and 3. we attempted to abort, this would crash the tests`, ) }) @@ -690,7 +690,7 @@ describe('conditional skipping of asyncThunks', () => { }, payload: undefined, type: 'test/rejected', - }) + }), ) }) }) @@ -736,7 +736,7 @@ describe('unwrapResult', () => { }) const unwrapPromise = asyncThunk()(dispatch, getState, extra).then( - unwrapResult + unwrapResult, ) await expect(unwrapPromise).resolves.toBe('fulfilled!') @@ -752,14 +752,14 @@ describe('unwrapResult', () => { }) const unwrapPromise = asyncThunk()(dispatch, getState, extra).then( - unwrapResult + unwrapResult, ) await expect(unwrapPromise).rejects.toEqual(miniSerializeError(error)) const unwrapPromise2 = asyncThunk()(dispatch, getState, extra) await expect(unwrapPromise2.unwrap()).rejects.toEqual( - miniSerializeError(error) + miniSerializeError(error), ) }) test('rejectWithValue case', async () => { @@ -768,7 +768,7 @@ describe('unwrapResult', () => { }) const unwrapPromise = asyncThunk()(dispatch, getState, extra).then( - unwrapResult + unwrapResult, ) await expect(unwrapPromise).rejects.toBe('rejectWithValue!') @@ -800,7 +800,7 @@ describe('idGenerator option', () => { async (args: void, { requestId }) => { generatedRequestId = requestId }, - { idGenerator } + { idGenerator }, ) // dispatching the thunks should be using the custom id generator @@ -824,7 +824,7 @@ describe('idGenerator option', () => { 'test', async (args: void, { requestId }) => { generatedRequestId = requestId - } + }, ) // dispatching the default options thunk should still generate an id, // but not using the custom id generator @@ -832,10 +832,10 @@ describe('idGenerator option', () => { expect(generatedRequestId).toEqual(promise3.requestId) expect(promise3.requestId).not.toEqual('') expect(promise3.requestId).not.toEqual( - expect.stringContaining('fake-random-id') + expect.stringContaining('fake-random-id'), ) expect((await promise3).meta.requestId).not.toEqual( - expect.stringContaining('fake-fandom-id') + expect.stringContaining('fake-fandom-id'), ) }) @@ -847,7 +847,7 @@ describe('idGenerator option', () => { async (args: any, { requestId }) => { generatedRequestId = requestId }, - { idGenerator: customIdGenerator } + { idGenerator: customIdGenerator }, ) const thunkArg = 1 diff --git a/packages/toolkit/src/tests/createDraftSafeSelector.test.ts b/packages/toolkit/src/tests/createDraftSafeSelector.test.ts index ab95fc48d8..e25ac95d5e 100644 --- a/packages/toolkit/src/tests/createDraftSafeSelector.test.ts +++ b/packages/toolkit/src/tests/createDraftSafeSelector.test.ts @@ -28,7 +28,7 @@ test('handles drafts correctly', () => { const unsafeSelector = createSelector(selectSelf, (state) => state.value) const draftSafeSelector = createDraftSafeSelector( selectSelf, - (state) => state.value + (state) => state.value, ) produce({ value: 1 }, (state) => { diff --git a/packages/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts b/packages/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts index cb70812d46..cc7ec2f1d8 100644 --- a/packages/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts +++ b/packages/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts @@ -34,14 +34,14 @@ describe(createDraftSafeSelector.withTypes, () => { expect(createTypedDraftSafeSelector.withTypes).toEqual(expect.any(Function)) expect(createTypedDraftSafeSelector.withTypes().withTypes).toEqual( - expect.any(Function) + expect.any(Function), ) expect(createTypedDraftSafeSelector).toBe(createDraftSafeSelector) const selectTodoIds = createTypedDraftSafeSelector( [(state) => state.todos], - (todos) => todos.map(({ id }) => id) + (todos) => todos.map(({ id }) => id), ) expect(selectTodoIds(rootState)).to.be.an('array').that.is.not.empty diff --git a/packages/toolkit/src/tests/createReducer.test.ts b/packages/toolkit/src/tests/createReducer.test.ts index 5d794c78b7..e5ea7365a3 100644 --- a/packages/toolkit/src/tests/createReducer.test.ts +++ b/packages/toolkit/src/tests/createReducer.test.ts @@ -89,11 +89,11 @@ describe('createReducer', () => { } expect(wrapper).toThrowError( - /The object notation for `createReducer` has been removed/ + /The object notation for `createReducer` has been removed/, ) expect(wrapper).toThrowError( - /The object notation for `createReducer` has been removed/ + /The object notation for `createReducer` has been removed/, ) }) @@ -145,7 +145,7 @@ describe('createReducer', () => { const mutateStateOutsideReducer = () => (result[0].text = 'edited') expect(mutateStateOutsideReducer).toThrowError( - 'Cannot add property text, object is not extensible' + 'Cannot add property text, object is not extensible', ) }) @@ -157,12 +157,12 @@ describe('createReducer', () => { const mutateStateOutsideReducer = () => (frozenInitialState[0].text = 'edited') expect(mutateStateOutsideReducer).toThrowError( - /Cannot assign to read only property/ + /Cannot assign to read only property/, ) }) test('does not throw error if initial state is not draftable', () => { expect(() => - createReducer(new URLSearchParams(), () => {}) + createReducer(new URLSearchParams(), () => {}), ).not.toThrowError() }) }) @@ -263,7 +263,7 @@ describe('createReducer', () => { const reducer = createReducer(0, (builder) => builder .addCase(increment, (state, action) => state + action.payload) - .addCase(decrement, (state, action) => state - action.payload) + .addCase(decrement, (state, action) => state - action.payload), ) expect(reducer(0, increment(5))).toBe(5) expect(reducer(5, decrement(5))).toBe(0) @@ -274,13 +274,13 @@ describe('createReducer', () => { .addCase( 'increment', (state, action: { type: 'increment'; payload: number }) => - state + action.payload + state + action.payload, ) .addCase( 'decrement', (state, action: { type: 'decrement'; payload: number }) => - state - action.payload - ) + state - action.payload, + ), ) expect(reducer(0, increment(5))).toBe(5) expect(reducer(5, decrement(5))).toBe(0) @@ -292,8 +292,8 @@ describe('createReducer', () => { .addCase( 'decrement', (state, action: { type: 'decrement'; payload: number }) => - state - action.payload - ) + state - action.payload, + ), ) expect(reducer(0, increment(5))).toBe(5) expect(reducer(5, decrement(5))).toBe(0) @@ -302,11 +302,11 @@ describe('createReducer', () => { const reducer = createReducer(0, (builder) => builder.addCase( 'decrement', - (state, action: { type: 'decrement'; payload: number }) => {} - ) + (state, action: { type: 'decrement'; payload: number }) => {}, + ), ) expect(() => reducer(5, decrement(5))).toThrowErrorMatchingInlineSnapshot( - `[Error: A case reducer on a non-draftable value must not return undefined]` + `[Error: A case reducer on a non-draftable value must not return undefined]`, ) }) test('allows you to return undefined if the state was null, thus skipping an update', () => { @@ -318,8 +318,8 @@ describe('createReducer', () => { return state - action.payload } return undefined - } - ) + }, + ), ) expect(reducer(0, decrement(5))).toBe(-5) expect(reducer(null, decrement(5))).toBe(null) @@ -330,8 +330,8 @@ describe('createReducer', () => { 'decrement', (state, action: { type: 'decrement'; payload: number }) => { return null - } - ) + }, + ), ) expect(reducer(5, decrement(5))).toBe(null) }) @@ -340,8 +340,8 @@ describe('createReducer', () => { builder.addCase( 'decrement', (state, action: { type: 'decrement'; payload: number }) => - state - action.payload - ) + state - action.payload, + ), ) expect(reducer(5, decrement(5))).toBe(0) }) @@ -351,20 +351,20 @@ describe('createReducer', () => { builder .addCase(increment, (state, action) => state + action.payload) .addCase(increment, (state, action) => state + action.payload) - .addCase(decrement, (state, action) => state - action.payload) - ) + .addCase(decrement, (state, action) => state - action.payload), + ), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']` + `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`, ) expect(() => createReducer(0, (builder) => builder .addCase(increment, (state, action) => state + action.payload) .addCase('increment', (state) => state + 1) - .addCase(decrement, (state, action) => state - action.payload) - ) + .addCase(decrement, (state, action) => state - action.payload), + ), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']` + `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`, ) }) @@ -373,16 +373,16 @@ describe('createReducer', () => { type: 'custom_action', payload, }) - customActionCreator.type = "" + customActionCreator.type = '' expect(() => createReducer(0, (builder) => builder.addCase( customActionCreator, - (state, action) => state + action.payload - ) - ) + (state, action) => state + action.payload, + ), + ), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`builder.addCase\` cannot be called with an empty action type]` + `[Error: \`builder.addCase\` cannot be called with an empty action type]`, ) }) }) @@ -398,14 +398,14 @@ describe('createReducer', () => { }) const numberActionMatcher = ( - a: UnknownAction + a: UnknownAction, ): a is PayloadAction => isPlainObject(a.meta) && 'type' in a.meta && (a.meta as Record<'type', unknown>).type === 'number_action' const stringActionMatcher = ( - a: UnknownAction + a: UnknownAction, ): a is PayloadAction => isPlainObject(a.meta) && 'type' in a.meta && @@ -425,7 +425,7 @@ describe('createReducer', () => { }) .addMatcher(stringActionMatcher, (state) => { state.stringActions += 1 - }) + }), ) expect(reducer(undefined, incrementBy(1))).toEqual({ numberActions: 1, @@ -452,7 +452,7 @@ describe('createReducer', () => { .addDefaultCase((state) => { state.numberActions = -1 state.stringActions = -1 - }) + }), ) expect(reducer(undefined, { type: 'somethingElse' })).toEqual({ numberActions: -1, @@ -473,7 +473,7 @@ describe('createReducer', () => { }) .addMatcher(numberActionMatcher, (state) => { state.numberActions = state.numberActions * 10 + 3 - }) + }), ) expect(reducer(undefined, incrementBy(1))).toEqual({ numberActions: 123, @@ -492,7 +492,7 @@ describe('createReducer', () => { const reducer = createReducer(initialState, (builder) => builder.addMatcher(incrementBy.match, (state) => { state.numberActions += 100 - }) + }), ) expect(reducer(undefined, incrementBy(1))).toEqual({ numberActions: 100, @@ -504,33 +504,33 @@ describe('createReducer', () => { createReducer(initialState, (builder: any) => builder .addMatcher(numberActionMatcher, () => {}) - .addCase(incrementBy, () => {}) - ) + .addCase(incrementBy, () => {}), + ), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`builder.addCase\` should only be called before calling \`builder.addMatcher\`]` + `[Error: \`builder.addCase\` should only be called before calling \`builder.addMatcher\`]`, ) expect(() => createReducer(initialState, (builder: any) => - builder.addDefaultCase(() => {}).addCase(incrementBy, () => {}) - ) + builder.addDefaultCase(() => {}).addCase(incrementBy, () => {}), + ), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`builder.addCase\` should only be called before calling \`builder.addDefaultCase\`]` + `[Error: \`builder.addCase\` should only be called before calling \`builder.addDefaultCase\`]`, ) expect(() => createReducer(initialState, (builder: any) => builder .addDefaultCase(() => {}) - .addMatcher(numberActionMatcher, () => {}) - ) + .addMatcher(numberActionMatcher, () => {}), + ), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`builder.addMatcher\` should only be called before calling \`builder.addDefaultCase\`]` + `[Error: \`builder.addMatcher\` should only be called before calling \`builder.addDefaultCase\`]`, ) expect(() => createReducer(initialState, (builder: any) => - builder.addDefaultCase(() => {}).addDefaultCase(() => {}) - ) + builder.addDefaultCase(() => {}).addDefaultCase(() => {}), + ), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`builder.addDefaultCase\` can only be called once]` + `[Error: \`builder.addDefaultCase\` can only be called once]`, ) }) }) @@ -547,7 +547,7 @@ function behavesLikeReducer(todosReducer: TodosReducer) { todosReducer([], { type: 'ADD_TODO', payload: { newTodo: { text: 'Run the tests' } }, - }) + }), ).toEqual([ { text: 'Run the tests', @@ -566,8 +566,8 @@ function behavesLikeReducer(todosReducer: TodosReducer) { { type: 'ADD_TODO', payload: { newTodo: { text: 'Use Redux' } }, - } - ) + }, + ), ).toEqual([ { text: 'Run the tests', @@ -594,8 +594,8 @@ function behavesLikeReducer(todosReducer: TodosReducer) { { type: 'ADD_TODO', payload: { newTodo: { text: 'Fix the tests' } }, - } - ) + }, + ), ).toEqual([ { text: 'Run the tests', @@ -628,8 +628,8 @@ function behavesLikeReducer(todosReducer: TodosReducer) { { type: 'TOGGLE_TODO', payload: { index: 0 }, - } - ) + }, + ), ).toEqual([ { text: 'Run the tests', diff --git a/packages/toolkit/src/tests/createSlice.test.ts b/packages/toolkit/src/tests/createSlice.test.ts index 94b67126e1..3f6bdc5d90 100644 --- a/packages/toolkit/src/tests/createSlice.test.ts +++ b/packages/toolkit/src/tests/createSlice.test.ts @@ -33,7 +33,7 @@ describe('createSlice', () => { state * action.payload, }, initialState: 0, - }) + }), ).toThrowError() }) }) @@ -49,7 +49,7 @@ describe('createSlice', () => { state * action.payload, }, initialState: 0, - }) + }), ).toThrowError() }) }) @@ -69,7 +69,7 @@ describe('createSlice', () => { }) expect(getLog().log).toBe( - 'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`' + 'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`', ) }) }) @@ -121,7 +121,7 @@ describe('createSlice', () => { name: 'params', initialState: new URLSearchParams(), reducers: {}, - }) + }), ).not.toThrowError() }) }) @@ -162,7 +162,7 @@ describe('createSlice', () => { name: 'params', initialState: () => new URLSearchParams(), reducers: {}, - }) + }), ).not.toThrowError() }) }) @@ -199,7 +199,7 @@ describe('createSlice', () => { extraReducers: (builder) => { builder.addCase( addMore, - (state, action) => state + action.payload.amount + (state, action) => state + action.payload.amount, ) }, @@ -223,7 +223,7 @@ describe('createSlice', () => { extraReducers: (builder) => builder.addCase( increment, - (state, action) => state + action.payload + (state, action) => state + action.payload, ), }) expect(slice.reducer(0, increment(5))).toBe(5) @@ -238,7 +238,7 @@ describe('createSlice', () => { builder.addCase( 'increment', (state, action: { type: 'increment'; payload: number }) => - state + action.payload + state + action.payload, ), }) expect(slice.reducer(0, increment(5))).toBe(5) @@ -257,7 +257,7 @@ describe('createSlice', () => { }) slice.reducer(undefined, { type: 'unrelated' }) }).toThrowErrorMatchingInlineSnapshot( - `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']` + `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`, ) }) @@ -270,7 +270,7 @@ describe('createSlice', () => { builder.addMatcher( increment.match, (state, action: { type: 'increment'; payload: number }) => - state + action.payload + state + action.payload, ), }) expect(slice.reducer(0, increment(5))).toBe(5) @@ -284,7 +284,7 @@ describe('createSlice', () => { extraReducers: (builder) => builder.addDefaultCase( (state, action) => - state + (action as PayloadAction).payload + state + (action as PayloadAction).payload, ), }) expect(slice.reducer(0, increment(5))).toBe(5) @@ -333,7 +333,7 @@ describe('createSlice', () => { testSlice.reducer(0, testSlice.actions.testReducer('testPayload')) expect(reducer).toHaveBeenCalledWith( 0, - expect.objectContaining({ payload: 'testPayload' }) + expect.objectContaining({ payload: 'testPayload' }), ) }) }) @@ -371,23 +371,23 @@ describe('createSlice', () => { }) expect(first.reducer(undefined, { type: 'unrelated' })).toBe( - 'firstInitial' + 'firstInitial', ) expect(first.reducer(undefined, first.actions.something())).toBe( - 'firstSomething' + 'firstSomething', ) expect(first.reducer(undefined, second.actions.other())).toBe( - 'firstOther' + 'firstOther', ) expect(second.reducer(undefined, { type: 'unrelated' })).toBe( - 'secondInitial' + 'secondInitial', ) expect(second.reducer(undefined, first.actions.something())).toBe( - 'secondSomething' + 'secondSomething', ) expect(second.reducer(undefined, second.actions.other())).toBe( - 'secondOther' + 'secondOther', ) }) }) @@ -425,7 +425,7 @@ describe('createSlice', () => { } expect(wrapper).toThrowError( - /The object notation for `createSlice.extraReducers` has been removed/ + /The object notation for `createSlice.extraReducers` has been removed/, ) dummySlice = (createSlice as CreateSlice)({ @@ -438,7 +438,7 @@ describe('createSlice', () => { }, }) expect(wrapper).toThrowError( - /The object notation for `createSlice.extraReducers` has been removed/ + /The object notation for `createSlice.extraReducers` has been removed/, ) }) @@ -461,7 +461,7 @@ describe('createSlice', () => { } expect(wrapper).toThrowError( - /The object notation for `createSlice.extraReducers` has been removed/ + /The object notation for `createSlice.extraReducers` has been removed/, ) vi.unstubAllEnvs() @@ -476,7 +476,7 @@ describe('createSlice', () => { selectSlice: (state) => state, selectMultiple: Object.assign( (state: number, multiplier: number) => state * multiplier, - { test: 0 } + { test: 0 }, ), }, }) @@ -493,7 +493,7 @@ describe('createSlice', () => { number: slice.getInitialState(), } const { selectSlice, selectMultiple } = slice.getSelectors( - (state: typeof customState) => state.number + (state: typeof customState) => state.number, ) expect(selectSlice(customState)).toBe(slice.getInitialState()) expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2) @@ -539,22 +539,22 @@ describe('createSlice', () => { // selector returns initial state if undefined in real state expect(injectedSlice.selectSlice(uninjectedState)).toBe( - slice.getInitialState() + slice.getInitialState(), ) expect(injectedSlice.selectors.selectMultiple({}, 1)).toBe( - slice.getInitialState() + slice.getInitialState(), ) expect(injectedSlice.getSelectors().selectMultiple(undefined, 1)).toBe( - slice.getInitialState() + slice.getInitialState(), ) const injectedState = combinedReducer(undefined, increment()) expect(injectedSlice.selectSlice(injectedState)).toBe( - slice.getInitialState() + 1 + slice.getInitialState() + 1, ) expect(injectedSlice.selectors.selectMultiple(injectedState, 1)).toBe( - slice.getInitialState() + 1 + slice.getInitialState() + 1, ) }) it('allows providing a custom name to inject under', () => { @@ -585,10 +585,10 @@ describe('createSlice', () => { const injectedState = combinedReducer(undefined, increment()) expect(injected.selectSlice(injectedState)).toBe( - slice.getInitialState() + 1 + slice.getInitialState() + 1, ) expect(injected.selectors.selectMultiple(injectedState, 2)).toBe( - (slice.getInitialState() + 1) * 2 + (slice.getInitialState() + 1) * 2, ) const injected2 = slice.injectInto(combinedReducer, { @@ -598,10 +598,10 @@ describe('createSlice', () => { const injected2State = combinedReducer(undefined, increment()) expect(injected2.selectSlice(injected2State)).toBe( - slice.getInitialState() + 1 + slice.getInitialState() + 1, ) expect(injected2.selectors.selectMultiple(injected2State, 2)).toBe( - (slice.getInitialState() + 1) * 2 + (slice.getInitialState() + 1) * 2, ) }) it('avoids incorrectly caching selectors', () => { @@ -629,9 +629,9 @@ describe('createSlice', () => { expect(() => // @ts-expect-error - slice.getSelectors().selectMultiple(undefined, 1) + slice.getSelectors().selectMultiple(undefined, 1), ).toThrowErrorMatchingInlineSnapshot( - `[Error: selectState returned undefined for an uninjected slice reducer]` + `[Error: selectState returned undefined for an uninjected slice reducer]`, ) const injected2 = slice.injectInto(combinedReducer, { @@ -651,9 +651,9 @@ describe('createSlice', () => { name: 'test', initialState: [] as any[], reducers: (create) => ({ thunk: create.asyncThunk(() => {}) }), - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: Cannot use \`create.asyncThunk\` in the built-in \`createSlice\`. Use \`buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })\` to create a customised version of \`createSlice\`.]` + `[Error: Cannot use \`create.asyncThunk\` in the built-in \`createSlice\`. Use \`buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })\` to create a customised version of \`createSlice\`.]`, ) }) const createAppSlice = buildCreateSlice({ @@ -681,7 +681,7 @@ describe('createSlice', () => { function payloadCreator(arg, api) { return Promise.resolve('resolved payload') }, - { pending, fulfilled, rejected, settled } + { pending, fulfilled, rejected, settled }, ), }), }) @@ -725,7 +725,7 @@ describe('createSlice', () => { function payloadCreator(arg, api): any { throw new Error('') }, - { pending, fulfilled, rejected, settled } + { pending, fulfilled, rejected, settled }, ), }), }) @@ -779,7 +779,7 @@ describe('createSlice', () => { fulfilled, rejected, settled, - } + }, ), }), }) @@ -817,7 +817,7 @@ describe('createSlice', () => { function payloadCreator(arg, api) { return Promise.resolve('resolved payload') }, - { pending, fulfilled, settled } + { pending, fulfilled, settled }, ), }), }) @@ -833,9 +833,9 @@ describe('createSlice', () => { slice.actions.thunkReducers.rejected( new Error('test'), 'fakeRequestId', - {} - ) - ) + {}, + ), + ), ).not.toThrow() }) @@ -852,13 +852,16 @@ describe('createSlice', () => { }), (state, action) => { state.push(action) - } + }, ), }), }) expect( - slice.reducer([], slice.actions.prepared('test', 1, { message: 'err' })) + slice.reducer( + [], + slice.actions.prepared('test', 1, { message: 'err' }), + ), ).toMatchInlineSnapshot(` [ { @@ -890,9 +893,9 @@ describe('createSlice', () => { }, }, }), - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: Please use the \`create.preparedReducer\` notation for prepared action creators with the \`create\` notation.]` + `[Error: Please use the \`create.preparedReducer\` notation for prepared action creators with the \`create\` notation.]`, ) }) }) diff --git a/packages/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts b/packages/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts index dec7789032..63679ba0d8 100644 --- a/packages/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts +++ b/packages/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts @@ -151,7 +151,7 @@ describe('createImmutableStateInvariantMiddleware', () => { try { dispatch({ type: 'SOME_ACTION' }) expect(getLog().log).toMatch( - /^ImmutableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./ + /^ImmutableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./, ) } finally { restore() diff --git a/packages/toolkit/src/tests/matchers.test-d.ts b/packages/toolkit/src/tests/matchers.test-d.ts index 269debcfd8..12d3246eec 100644 --- a/packages/toolkit/src/tests/matchers.test-d.ts +++ b/packages/toolkit/src/tests/matchers.test-d.ts @@ -55,7 +55,7 @@ describe('type tests', () => { prop1: 1, prop3: 3, } - } + }, ) const asyncThunk2 = createAsyncThunk<{ prop1: number; prop2: number }>( @@ -66,7 +66,7 @@ describe('type tests', () => { prop1: 1, prop2: 2, } - } + }, ) if (isAnyOf(asyncThunk1.fulfilled, asyncThunk2.fulfilled)(action)) { @@ -158,7 +158,7 @@ describe('type tests', () => { prop1: 1, prop3: 3, } - } + }, ) if (isAllOf(asyncThunk1.fulfilled, isSpecialAction)(action)) { @@ -288,10 +288,10 @@ describe('type tests', () => { const thunk2 = createAsyncThunk('b', () => 'b') const interestingThunks = [thunk1, thunk2] const interestingPendingThunks = interestingThunks.map( - (thunk) => thunk.pending + (thunk) => thunk.pending, ) const interestingFulfilledThunks = interestingThunks.map( - (thunk) => thunk.fulfilled + (thunk) => thunk.fulfilled, ) const isLoading = isAnyOf(...interestingPendingThunks) diff --git a/packages/toolkit/src/tests/matchers.test.ts b/packages/toolkit/src/tests/matchers.test.ts index 54dbbed37e..11a6fdb8cd 100644 --- a/packages/toolkit/src/tests/matchers.test.ts +++ b/packages/toolkit/src/tests/matchers.test.ts @@ -70,7 +70,7 @@ describe('isAnyOf', () => { expect(isAnyOf(thunkA.fulfilled, thunkB.fulfilled)(action)).toEqual(true) expect( - isAnyOf(thunkA.pending, thunkA.rejected, thunkB.fulfilled)(action) + isAnyOf(thunkA.pending, thunkA.rejected, thunkB.fulfilled)(action), ).toEqual(false) }) @@ -133,13 +133,13 @@ describe('isAllOf', () => { const specialThunkAction = thunkA.fulfilled('SPECIAL', 'fakeRequestId') expect(isAllOf(thunkA.fulfilled, isActionSpecial)(specialThunkAction)).toBe( - true + true, ) const ordinaryThunkAction = thunkA.fulfilled('ORDINARY', 'fakeRequestId') expect( - isAllOf(thunkA.fulfilled, isActionSpecial)(ordinaryThunkAction) + isAllOf(thunkA.fulfilled, isActionSpecial)(ordinaryThunkAction), ).toBe(false) }) }) @@ -162,7 +162,7 @@ describe('isPending', () => { const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(isPending()(rejectedAction)).toBe(false) @@ -180,7 +180,7 @@ describe('isPending', () => { function testPendingAction( thunk: typeof thunkA | typeof thunkB | typeof thunkC, - expected: boolean + expected: boolean, ) { const pendingAction = thunk.pending('fakeRequestId') expect(matchAC(pendingAction)).toBe(expected) @@ -188,7 +188,7 @@ describe('isPending', () => { const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(matchAC(rejectedAction)).toBe(false) @@ -219,7 +219,7 @@ describe('isRejected', () => { const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(isRejected()(rejectedAction)).toBe(true) expect(isRejected(rejectedAction)).toBe(true) @@ -238,14 +238,14 @@ describe('isRejected', () => { function testRejectedAction( thunk: typeof thunkA | typeof thunkB | typeof thunkC, - expected: boolean + expected: boolean, ) { const pendingAction = thunk.pending('fakeRequestId') expect(matchAC(pendingAction)).toBe(false) const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(matchAC(rejectedAction)).toBe(expected) expect(matchB(rejectedAction)).toBe(!expected) @@ -279,7 +279,7 @@ describe('isRejectedWithValue', () => { const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(isRejectedWithValue()(rejectedAction)).toBe(false) @@ -310,14 +310,14 @@ describe('isRejectedWithValue', () => { async function testRejectedAction( thunk: typeof thunkA | typeof thunkB | typeof thunkC, - expected: boolean + expected: boolean, ) { const pendingAction = thunk.pending('fakeRequestId') expect(matchAC(pendingAction)).toBe(false) const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) // rejected-with-value is a narrower requirement than rejected expect(matchAC(rejectedAction)).toBe(false) @@ -359,7 +359,7 @@ describe('isFulfilled', () => { const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(isFulfilled()(rejectedAction)).toBe(false) @@ -378,14 +378,14 @@ describe('isFulfilled', () => { function testFulfilledAction( thunk: typeof thunkA | typeof thunkB | typeof thunkC, - expected: boolean + expected: boolean, ) { const pendingAction = thunk.pending('fakeRequestId') expect(matchAC(pendingAction)).toBe(false) const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(matchAC(rejectedAction)).toBe(false) @@ -418,7 +418,7 @@ describe('isAsyncThunkAction', () => { const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(matcher(rejectedAction)).toBe(true) @@ -436,7 +436,7 @@ describe('isAsyncThunkAction', () => { function testAllActions( thunk: typeof thunkA | typeof thunkB | typeof thunkC, - expected: boolean + expected: boolean, ) { const pendingAction = thunk.pending('fakeRequestId') expect(matchAC(pendingAction)).toBe(expected) @@ -444,7 +444,7 @@ describe('isAsyncThunkAction', () => { const rejectedAction = thunk.rejected( new Error('rejected'), - 'fakeRequestId' + 'fakeRequestId', ) expect(matchAC(rejectedAction)).toBe(expected) expect(matchB(rejectedAction)).toBe(!expected) diff --git a/packages/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts b/packages/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts index d9413671ed..0d0ffd7630 100644 --- a/packages/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts +++ b/packages/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts @@ -362,7 +362,7 @@ describe('serializableStateInvariantMiddleware', () => { new Tuple( createSerializableStateInvariantMiddleware({ ignoredActionPaths: [], - }) + }), ), }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } }) @@ -386,7 +386,7 @@ describe('serializableStateInvariantMiddleware', () => { new Tuple( createSerializableStateInvariantMiddleware({ ignoredActionPaths: ['payload', 'meta.arg'], - }) + }), ), }).dispatch({ type: 'test', @@ -404,7 +404,7 @@ describe('serializableStateInvariantMiddleware', () => { new Tuple( createSerializableStateInvariantMiddleware({ ignoredActionPaths: [/^payload\..*$/], - }) + }), ), }).dispatch({ type: 'test', @@ -519,7 +519,7 @@ describe('serializableStateInvariantMiddleware', () => { return true }, ignoreState: true, - }) + }), ), }) @@ -548,7 +548,7 @@ describe('serializableStateInvariantMiddleware', () => { }, ignoreState: true, ignoreActions: true, - }) + }), ), }) @@ -580,7 +580,7 @@ describe('serializableStateInvariantMiddleware', () => { payload: new Array(10000).fill({ value: 'more' }), }) expect(getLog().log).toMatch( - /^SerializableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./ + /^SerializableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./, ) }) @@ -626,7 +626,7 @@ describe('serializableStateInvariantMiddleware', () => { }) const state = createNextState([], () => - new Array(50).fill(0).map((x, i) => ({ i })) + new Array(50).fill(0).map((x, i) => ({ i })), ) expect(isNestedFrozen(state)).toBe(true) diff --git a/packages/toolkit/src/tests/utils/CustomMatchers.d.ts b/packages/toolkit/src/tests/utils/CustomMatchers.d.ts index 46a58c74d0..955e51db36 100644 --- a/packages/toolkit/src/tests/utils/CustomMatchers.d.ts +++ b/packages/toolkit/src/tests/utils/CustomMatchers.d.ts @@ -1,11 +1,11 @@ -import type { Assertion, AsymmetricMatchersContaining } from "vitest" +import type { Assertion, AsymmetricMatchersContaining } from 'vitest' interface CustomMatchers { toHaveConsoleOutput(expectedOutput: string): Promise toMatchSequence(...matchers: Array<(arg: any) => boolean>): R } -declare module "vitest" { +declare module 'vitest' { interface Assertion extends CustomMatchers {} interface AsymmetricMatchersContaining extends CustomMatchers {} } @@ -14,4 +14,4 @@ declare global { namespace jest { interface Matchers extends CustomMatchers {} } -} \ No newline at end of file +} diff --git a/packages/toolkit/src/tests/utils/helpers.tsx b/packages/toolkit/src/tests/utils/helpers.tsx index 76fb1bb6a5..5ccedc434d 100644 --- a/packages/toolkit/src/tests/utils/helpers.tsx +++ b/packages/toolkit/src/tests/utils/helpers.tsx @@ -142,7 +142,7 @@ function normalize(str: string) { expect.extend({ async toHaveConsoleOutput( fn: () => void | Promise, - expectedOutput: string + expectedOutput: string, ) { const restore = mockConsole(createConsole()) await fn() @@ -190,7 +190,7 @@ export function setupApiStore< middleware: Middleware util: { resetApiState(): any } }, - R extends Record> = Record + R extends Record> = Record, >( api: A, extraReducers?: R, @@ -201,7 +201,7 @@ export function setupApiStore< prepend?: Middleware[] concat?: Middleware[] } - } = {} + } = {}, ) { const { middleware } = options const getStore = () => diff --git a/packages/toolkit/src/tsHelpers.ts b/packages/toolkit/src/tsHelpers.ts index d4d6a2f3e0..45c90aeaef 100644 --- a/packages/toolkit/src/tsHelpers.ts +++ b/packages/toolkit/src/tsHelpers.ts @@ -87,14 +87,14 @@ export type UnionToIntersection = ( // Appears to have a convenient side effect of ignoring `never` even if that's not what you specified export type ExcludeFromTuple = T extends [ infer Head, - ...infer Tail + ...infer Tail, ] ? ExcludeFromTuple : Acc type ExtractDispatchFromMiddlewareTuple< MiddlewareTuple extends readonly any[], - Acc extends {} + Acc extends {}, > = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple< Tail, @@ -102,17 +102,16 @@ type ExtractDispatchFromMiddlewareTuple< > : Acc -export type ExtractDispatchExtensions = M extends Tuple< - infer MiddlewareTuple -> - ? ExtractDispatchFromMiddlewareTuple - : M extends ReadonlyArray - ? ExtractDispatchFromMiddlewareTuple<[...M], {}> - : never +export type ExtractDispatchExtensions = + M extends Tuple + ? ExtractDispatchFromMiddlewareTuple + : M extends ReadonlyArray + ? ExtractDispatchFromMiddlewareTuple<[...M], {}> + : never type ExtractStoreExtensionsFromEnhancerTuple< EnhancerTuple extends readonly any[], - Acc extends {} + Acc extends {}, > = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple< Tail, @@ -120,21 +119,22 @@ type ExtractStoreExtensionsFromEnhancerTuple< > : Acc -export type ExtractStoreExtensions = E extends Tuple - ? ExtractStoreExtensionsFromEnhancerTuple - : E extends ReadonlyArray - ? UnionToIntersection< - E[number] extends StoreEnhancer - ? Ext extends {} - ? IsAny - : {} - : {} - > - : never +export type ExtractStoreExtensions = + E extends Tuple + ? ExtractStoreExtensionsFromEnhancerTuple + : E extends ReadonlyArray + ? UnionToIntersection< + E[number] extends StoreEnhancer + ? Ext extends {} + ? IsAny + : {} + : {} + > + : never type ExtractStateExtensionsFromEnhancerTuple< EnhancerTuple extends readonly any[], - Acc extends {} + Acc extends {}, > = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple< Tail, @@ -145,17 +145,18 @@ type ExtractStateExtensionsFromEnhancerTuple< > : Acc -export type ExtractStateExtensions = E extends Tuple - ? ExtractStateExtensionsFromEnhancerTuple - : E extends ReadonlyArray - ? UnionToIntersection< - E[number] extends StoreEnhancer - ? StateExt extends {} - ? IsAny - : {} - : {} - > - : never +export type ExtractStateExtensions = + E extends Tuple + ? ExtractStateExtensionsFromEnhancerTuple + : E extends ReadonlyArray + ? UnionToIntersection< + E[number] extends StoreEnhancer + ? StateExt extends {} + ? IsAny + : {} + : {} + > + : never /** * Helper type. Passes T out again, but boxes it in a way that it cannot @@ -185,7 +186,7 @@ export interface HasMatchFunction { } export const hasMatchFunction = ( - v: Matcher + v: Matcher, ): v is HasMatchFunction => { return v && typeof (v as HasMatchFunction).match === 'function' } @@ -194,11 +195,8 @@ export const hasMatchFunction = ( export type Matcher = HasMatchFunction | TypeGuard /** @public */ -export type ActionFromMatcher> = M extends Matcher< - infer T -> - ? T - : never +export type ActionFromMatcher> = + M extends Matcher ? T : never export type Id = { [K in keyof T]: T[K] } & {} @@ -221,7 +219,7 @@ export type SafePromise = Promise & { */ export function asSafePromise( promise: Promise, - fallback: (error: unknown) => Rejected + fallback: (error: unknown) => Rejected, ) { return promise.catch(fallback) as SafePromise } diff --git a/packages/toolkit/src/utils.ts b/packages/toolkit/src/utils.ts index 7dfe43dc3a..11c04ab83c 100644 --- a/packages/toolkit/src/utils.ts +++ b/packages/toolkit/src/utils.ts @@ -29,7 +29,7 @@ export function delay(ms: number) { export function find( iterable: Iterable, - comparator: (item: T) => boolean + comparator: (item: T) => boolean, ): T | undefined { for (const entry of iterable) { if (comparator(entry)) { @@ -55,10 +55,10 @@ export class Tuple = []> extends Array< } concat>( - items: Tuple + items: Tuple, ): Tuple<[...Items, ...AdditionalItems]> concat>( - items: AdditionalItems + items: AdditionalItems, ): Tuple<[...Items, ...AdditionalItems]> concat>( ...items: AdditionalItems @@ -68,10 +68,10 @@ export class Tuple = []> extends Array< } prepend>( - items: Tuple + items: Tuple, ): Tuple<[...AdditionalItems, ...Items]> prepend>( - items: AdditionalItems + items: AdditionalItems, ): Tuple<[...AdditionalItems, ...Items]> prepend>( ...items: AdditionalItems @@ -113,12 +113,12 @@ interface MapEmplaceHandler { export function emplace( map: Map, key: K, - handler: MapEmplaceHandler + handler: MapEmplaceHandler, ): V export function emplace( map: WeakMap, key: K, - handler: WeakMapEmplaceHandler + handler: WeakMapEmplaceHandler, ): V /** * Allow inserting a new value, or updating an existing one @@ -150,7 +150,7 @@ export function emplace( export function emplace( map: WeakMap, key: K, - handler: WeakMapEmplaceHandler + handler: WeakMapEmplaceHandler, ): V { if (map.has(key)) { let value = map.get(key) as V diff --git a/packages/toolkit/tsconfig.json b/packages/toolkit/tsconfig.json index 2c4a93a02e..f485db8fd3 100644 --- a/packages/toolkit/tsconfig.json +++ b/packages/toolkit/tsconfig.json @@ -5,7 +5,7 @@ "extends": "./tsconfig.test.json", "compilerOptions": { "skipLibCheck": true, - "rootDir": "." + "rootDir": ".", }, - "include": ["."] + "include": ["."], } diff --git a/packages/toolkit/tsup.config.ts b/packages/toolkit/tsup.config.ts index 5e43c847b2..a2726e030a 100644 --- a/packages/toolkit/tsup.config.ts +++ b/packages/toolkit/tsup.config.ts @@ -123,7 +123,7 @@ if (process.env.NODE_ENV === 'production') { module.exports = require('./${prefix}.production.min.cjs') } else { module.exports = require('./${prefix}.development.cjs') -}` +}`, ) } @@ -155,7 +155,7 @@ const mangleErrorsTransform: Plugin = { const tsconfig: NonNullable = path.join( __dirname, - './tsconfig.build.json' + './tsconfig.build.json', ) export default defineConfig((options) => { @@ -218,7 +218,7 @@ export default defineConfig((options) => { fs.copyFileSync( 'src/uncheckedindexed.ts', - path.join(outputFolder, 'uncheckedindexed.ts') + path.join(outputFolder, 'uncheckedindexed.ts'), ) } // TODO Copy/generate `.d.mts` files? diff --git a/website/src/css/custom.css b/website/src/css/custom.css index 4a61c52f6d..5bb4d94df8 100644 --- a/website/src/css/custom.css +++ b/website/src/css/custom.css @@ -173,12 +173,16 @@ a:visited { transform: rotateZ(180deg); -webkit-transition: -webkit-transform 0.2s linear; transition: -webkit-transform 0.2s linear; - transition-property: transform, -webkit-transform; + transition-property: + transform, + -webkit-transform; transition-duration: 0.2s, 0.2s; transition-timing-function: linear, linear; transition-delay: 0s, 0s; transition: transform 0.2s linear; - transition: transform 0.2s linear, -webkit-transform 0.2s linear; + transition: + transform 0.2s linear, + -webkit-transform 0.2s linear; color: var(--ifm-font-base-color) !important; } diff --git a/website/src/js/monokaiTheme.js b/website/src/js/monokaiTheme.js index e5c47f8be9..94e5cb451c 100644 --- a/website/src/js/monokaiTheme.js +++ b/website/src/js/monokaiTheme.js @@ -1,62 +1,62 @@ module.exports = { plain: { color: '#f8f8f2', - backgroundColor: '#272822' + backgroundColor: '#272822', }, styles: [ { types: ['comment', 'prolog', 'doctype', 'cdata'], style: { - color: '#778090' - } + color: '#778090', + }, }, { types: ['punctuation'], style: { - color: '#F8F8F2' - } + color: '#F8F8F2', + }, }, { types: ['property', 'tag', 'constant', 'symbol', 'deleted'], style: { - color: '#F92672' - } + color: '#F92672', + }, }, { types: ['boolean', 'number'], style: { - color: '#AE81FF' - } + color: '#AE81FF', + }, }, { types: ['selector', 'attr-name', 'string', 'char', 'builtin', 'inserted'], style: { - color: '#a6e22e' - } + color: '#a6e22e', + }, }, { types: ['operator', 'entity', 'url', 'variable'], style: { - color: '#F8F8F2' - } + color: '#F8F8F2', + }, }, { types: ['atrule', 'attr-value', 'function'], style: { - color: '#E6D874' - } + color: '#E6D874', + }, }, { types: ['keyword'], style: { - color: '#F92672' - } + color: '#F92672', + }, }, { types: ['regex', 'important'], style: { - color: '#FD971F' - } - } - ] + color: '#FD971F', + }, + }, + ], } diff --git a/website/src/pages/styles.module.css b/website/src/pages/styles.module.css index e8184048bd..54f977306d 100644 --- a/website/src/pages/styles.module.css +++ b/website/src/pages/styles.module.css @@ -99,7 +99,6 @@ margin-top: 0; } - .errorDetails { color: #ff6464; border-radius: 0.5rem;