@storyblok/react 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -88,12 +88,12 @@ That's it! All the features are enabled for you: the _Api Client_ for interactin
88
88
 
89
89
  #### 1. Fetching Content
90
90
 
91
- Inject `storyblokApi`:
91
+ Inject `useStoryblokApi`:
92
92
 
93
93
  ```js
94
- import { storyblokInit, apiPlugin } from "@storyblok/react";
94
+ import { storyblokInit, apiPlugin, useStoryblokApi } from "@storyblok/react";
95
95
 
96
- const { useStoryblokApi } = storyblokInit({
96
+ storyblokInit({
97
97
  accessToken: "YOUR_ACCESS_TOKEN",
98
98
  // bridge: false,
99
99
  // apiOptions: { },
@@ -106,6 +106,7 @@ const { useStoryblokApi } = storyblokInit({
106
106
  },
107
107
  });
108
108
 
109
+ const storyblokApi = useStoryblokApi()
109
110
  const { data } = await storyblokApi.get("cdn/stories", { version: "draft" });
110
111
  ```
111
112
 
@@ -162,6 +163,41 @@ export default Feature;
162
163
 
163
164
  Where `blok` is the actual blok data coming from [Storblok's Content Delivery API](https://www.storyblok.com/docs/api/content-delivery?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-react).
164
165
 
166
+ As an example, you can check in our [Next.js example demo](https://stackblitz.com/edit/react-next-sdk-demo?file=src%2Fpages%2Findex.jsx) how we use APIs provided from React SDK to combine with Next.js projects.
167
+
168
+ ```js
169
+ import { useStoryblokState, useStoryblokApi, StoryblokComponent } from "@storyblok/react";
170
+
171
+ export default function Home({ story: initialStory }) {
172
+ const story = useStoryblokState(initialStory);
173
+
174
+ if (!story.content) {
175
+ return <div>Loading...</div>;
176
+ }
177
+
178
+ return <StoryblokComponent blok={story.content} />;
179
+ }
180
+
181
+
182
+ export async function getStaticProps({ preview = false }) {
183
+ const storyblokApi = useStoryblokApi()
184
+ let { data } = await storyblokApi.get(`cdn/stories/react`, {
185
+ version: "draft"
186
+ });
187
+
188
+ return {
189
+ props: {
190
+ story: data ? data.story : false,
191
+ preview,
192
+ },
193
+ revalidate: 3600, // revalidate every hour
194
+ };
195
+ }
196
+ ```
197
+
198
+ If you'd like to have a React.js example demo, you can find it and try it out in your environement from here:
199
+ [React.js example demo](https://stackblitz.com/edit/react-sdk-demo)
200
+
165
201
  ### Features and API
166
202
 
167
203
  You can **choose the features to use** when you initialize the plugin. In that way, you can improve Web Performance by optimizing your page load and save some bytes.
@@ -211,6 +247,8 @@ sbBridge.on(["input", "published", "change"], (event) => {
211
247
  - **[Getting Started](https://www.storyblok.com/docs/guide/getting-started?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-react)**: Get a project ready in less than 5 minutes.
212
248
  - **[Storyblok CLI](https://github.com/storyblok/storyblok)**: A simple CLI for scaffolding Storyblok projects and fieldtypes.
213
249
  - **[Storyblok Next.js Technology Hub](https://www.storyblok.com/tc/nextjs)**: Learn how to develop your own Next.js applications that use Storyblok APIs to retrieve and manage content.
250
+ - **[Storyblok React.js example demo](https://stackblitz.com/edit/react-sdk-demo)**: See and try how React SDK works with React.js projects
251
+ - **[Storyblok Next.js example demo](https://stackblitz.com/edit/react-next-sdk-demo)**: See and try how React SDK works with Next.js projects
214
252
 
215
253
  ## ℹ️ More Resources
216
254
 
@@ -2,4 +2,4 @@ var ne=Object.defineProperty;var v=Object.getOwnPropertySymbols;var I=Object.pro
2
2
  * storyblok-js-client v0.0.0-development
3
3
  * Universal JavaScript SDK for Storyblok's API
4
4
  * (c) 2020-2022 Stobylok Team
5
- */function C(s){return typeof s=="number"&&s==s&&s!==1/0&&s!==-1/0}function A(s,e,t){if(!C(e))throw new TypeError("Expected `limit` to be a finite number");if(!C(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],o=[],n=0,i=function(){n++;var u=setTimeout(function(){n--,r.length>0&&i(),o=o.filter(function(d){return d!==u})},t);o.indexOf(u)<0&&o.push(u);var c=r.shift();c.resolve(s.apply(c.self,c.args))},a=function(){var u=arguments,c=this;return new Promise(function(d,k){r.push({resolve:d,reject:k,args:u,self:c}),n<e&&i()})};return a.abort=function(){o.forEach(clearTimeout),o=[],r.forEach(function(u){u.reject(new throttle.AbortError)}),r.length=0},a}A.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const z=function(s,e){if(!s)return null;let t={};for(let r in s){let o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t};var H={nodes:{horizontal_rule:s=>({singleTag:"hr"}),blockquote:s=>({tag:"blockquote"}),bullet_list:s=>({tag:"ul"}),code_block:s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),hard_break:s=>({singleTag:"br"}),heading:s=>({tag:"h"+s.attrs.level}),image:s=>({singleTag:[{tag:"img",attrs:z(s.attrs,["src","alt","title"])}]}),list_item:s=>({tag:"li"}),ordered_list:s=>({tag:"ol"}),paragraph:s=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(s){const e=g({},s.attrs),{linktype:t="url"}=s.attrs;return t==="email"&&(e.href="mailto:"+e.href),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:s=>({tag:[{tag:"span",attrs:s.attrs}]})}};class F{constructor(e){e||(e=H),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(function(o){const n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},i=/[&<>"']/g,a=RegExp(i.source);return o&&a.test(o)?o.replace(i,u=>n[u]):o}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let o="<"+r.tag;if(r.attrs)for(let n in r.attrs){let i=r.attrs[n];i!==null&&(o+=` ${n}="${i}"`)}return`${o}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const G=(s=0,e=s)=>{const t=Math.abs(e-s)||0,r=s<e?1:-1;return((o=0,n)=>[...Array(o)].map(n))(t,(o,n)=>n*r+s)},w=(s,e,t)=>{const r=[];for(const o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;const n=s[o],i=t?"":encodeURIComponent(o);let a;a=typeof n=="object"?w(n,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")};let b={},y={};class Q{constructor(e,t){if(!t){let n=e.region?"-"+e.region:"",i=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},e.headers),o=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,o=3),e.rateLimit!==void 0&&(o=e.rateLimit),this.richTextResolver=new F(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=A(this.throttledRequest,o,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=B.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(n=>e.responseInterceptor(n))}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=y[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,o){const n=this.factoryParamOptions(e,((i={},a=25,u=1)=>_(g({},i),{per_page:a,page:u}))(t,r,o));return this.cacheResponse(e,n)}get(e,t){let r="/"+e;const o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o)}async getAll(e,t={},r){const o=t.per_page||25,n="/"+e,i=n.split("/");r=r||i[i.length-1];const a=await this.makeRequest(n,t,o,1),u=Math.ceil(a.total/o);return((c=[],d)=>c.map(d).reduce((k,se)=>[...k,...se],[]))([a,...await(async(c=[],d)=>Promise.all(c.map(d)))(G(1,u),async c=>this.makeRequest(n,t,o,c+1))],c=>Object.values(c.data[r]))}post(e,t){let r="/"+e;return this.throttle("post",r,t)}put(e,t){let r="/"+e;return this.throttle("put",r,t)}delete(e,t){let r="/"+e;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get("cdn/stories/"+e,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.indexOf(e.component+"."+t)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t].constructor===Array){let o=[];e[t].forEach(n=>{this.relations[n]&&o.push(this._cleanCopy(this.relations[n]))}),e[t]=o}}}iterateTree(e,t){let r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(let n in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,n,t),this._insertLinks(o,n)),r(o[n])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const o=e.link_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const u=Math.min(o,a+i);n.push(e.link_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.links;r.forEach(o=>{this.links[o.uuid]=_(g({},o),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const u=Math.min(o,a+i);n.push(e.rel_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.rels;r.forEach(o=>{this.relations[o.uuid]=_(g({},o),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&await this.resolveLinks(e,t);for(const o in this.relations)this.iterateTree(this.relations[o],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(o=>{this.iterateTree(o,r)})}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(o,n)=>{let i=w({url:e,params:t}),a=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const c=await a.get(i);if(c)return o(c)}try{let c=await this.throttle("get",e,{params:t,paramsSerializer:k=>w(k)}),d={data:c.data,headers:c.headers};if(c.headers["per-page"]&&(d=Object.assign({},d,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return n(c);(d.data.story||d.data.stories)&&await this.resolveStories(d.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,d),d.data.cv&&(t.version=="draft"&&y[t.token]!=d.data.cv&&this.flushCache(),y[t.token]=d.data.cv),o(d)}catch(c){if(c.response&&c.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(u=1e3*r,new Promise(d=>setTimeout(d,u))),this.cacheResponse(e,t,r).then(o).catch(n);n(c)}var u})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get:e=>b[e],getAll:()=>b,set(e,t){b[e]=t},flush(){b={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}async flushCache(){return await this.cacheProvider().flush(),this}}var W=(s={})=>{const{apiOptions:e}=s;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new Q(e)}},X=s=>{if(typeof s!="object"||typeof s._editable=="undefined")return{};const e=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};const T=(s,e,t={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],o=>{o.action=="input"&&o.story.id===s?e(o.story):window.location.reload()})})}},Z=(s={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:o={}}=s;o.accessToken=o.accessToken||t;const n={bridge:e,apiOptions:o};let i={};return r.forEach(a=>{i=g(g({},i),a(n))}),e!==!1&&Y("https://app.storyblok.com/f/storyblok-v2-latest.js"),i},K=t=>{var r=t,{blok:s}=r,e=q(r,["blok"]);if(!s)return console.error("Please provide a 'blok' property to the StoryblokComponent"),E.default.createElement("div",null,"Please provide a blok property to the StoryblokComponent");const o=$(s.component);return o?E.default.createElement(o,N({blok:s},e)):""},ee=(s,e={},t={})=>{let[r,o]=h.useState({});return m?(T(r.id,n=>o(n),t),h.useEffect(async()=>{const{data:n}=await m.get(`cdn/stories/${s}`,e);o(n.story)},[]),r):(console.error("You can't use useStoryblok if you're not loading apiPlugin."),null)},te=(s={},e={})=>{let[t,r]=h.useState(s);return h.useEffect(()=>{T(t.id,o=>r(o),e)},[]),t};let m=null;const re=()=>(m||console.error("You can't use useStoryblokApi if you're not loading apiPlugin."),m);let S={};const $=s=>S[s]?S[s]:(console.error(`Component ${s} doesn't exist.`),!1),oe=(s={})=>{const{storyblokApi:e}=Z(s);m=e,S=s.components};l.StoryblokComponent=K,l.apiPlugin=W,l.getComponent=$,l.storyblokEditable=X,l.storyblokInit=oe,l.useStoryblok=ee,l.useStoryblokApi=re,l.useStoryblokBridge=T,l.useStoryblokState=te,Object.defineProperties(l,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
5
+ */function C(s){return typeof s=="number"&&s==s&&s!==1/0&&s!==-1/0}function A(s,e,t){if(!C(e))throw new TypeError("Expected `limit` to be a finite number");if(!C(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],o=[],n=0,i=function(){n++;var u=setTimeout(function(){n--,r.length>0&&i(),o=o.filter(function(d){return d!==u})},t);o.indexOf(u)<0&&o.push(u);var c=r.shift();c.resolve(s.apply(c.self,c.args))},a=function(){var u=arguments,c=this;return new Promise(function(d,k){r.push({resolve:d,reject:k,args:u,self:c}),n<e&&i()})};return a.abort=function(){o.forEach(clearTimeout),o=[],r.forEach(function(u){u.reject(new throttle.AbortError)}),r.length=0},a}A.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const z=function(s,e){if(!s)return null;let t={};for(let r in s){let o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t};var H={nodes:{horizontal_rule:s=>({singleTag:"hr"}),blockquote:s=>({tag:"blockquote"}),bullet_list:s=>({tag:"ul"}),code_block:s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),hard_break:s=>({singleTag:"br"}),heading:s=>({tag:"h"+s.attrs.level}),image:s=>({singleTag:[{tag:"img",attrs:z(s.attrs,["src","alt","title"])}]}),list_item:s=>({tag:"li"}),ordered_list:s=>({tag:"ol"}),paragraph:s=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(s){const e=g({},s.attrs),{linktype:t="url"}=s.attrs;return t==="email"&&(e.href="mailto:"+e.href),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:s=>({tag:[{tag:"span",attrs:s.attrs}]})}};class F{constructor(e){e||(e=H),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(function(o){const n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},i=/[&<>"']/g,a=RegExp(i.source);return o&&a.test(o)?o.replace(i,u=>n[u]):o}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let o="<"+r.tag;if(r.attrs)for(let n in r.attrs){let i=r.attrs[n];i!==null&&(o+=` ${n}="${i}"`)}return`${o}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const G=(s=0,e=s)=>{const t=Math.abs(e-s)||0,r=s<e?1:-1;return((o=0,n)=>[...Array(o)].map(n))(t,(o,n)=>n*r+s)},w=(s,e,t)=>{const r=[];for(const o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;const n=s[o],i=t?"":encodeURIComponent(o);let a;a=typeof n=="object"?w(n,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")};let b={},y={};class Q{constructor(e,t){if(!t){let n=e.region?"-"+e.region:"",i=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},e.headers),o=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,o=3),e.rateLimit!==void 0&&(o=e.rateLimit),this.richTextResolver=new F(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=A(this.throttledRequest,o,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=B.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(n=>e.responseInterceptor(n))}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=y[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,o){const n=this.factoryParamOptions(e,((i={},a=25,u=1)=>_(g({},i),{per_page:a,page:u}))(t,r,o));return this.cacheResponse(e,n)}get(e,t){let r="/"+e;const o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o)}async getAll(e,t={},r){const o=t.per_page||25,n="/"+e,i=n.split("/");r=r||i[i.length-1];const a=await this.makeRequest(n,t,o,1),u=Math.ceil(a.total/o);return((c=[],d)=>c.map(d).reduce((k,se)=>[...k,...se],[]))([a,...await(async(c=[],d)=>Promise.all(c.map(d)))(G(1,u),async c=>this.makeRequest(n,t,o,c+1))],c=>Object.values(c.data[r]))}post(e,t){let r="/"+e;return this.throttle("post",r,t)}put(e,t){let r="/"+e;return this.throttle("put",r,t)}delete(e,t){let r="/"+e;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get("cdn/stories/"+e,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.indexOf(e.component+"."+t)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t].constructor===Array){let o=[];e[t].forEach(n=>{this.relations[n]&&o.push(this._cleanCopy(this.relations[n]))}),e[t]=o}}}iterateTree(e,t){let r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(let n in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,n,t),this._insertLinks(o,n)),r(o[n])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const o=e.link_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const u=Math.min(o,a+i);n.push(e.link_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.links;r.forEach(o=>{this.links[o.uuid]=_(g({},o),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const u=Math.min(o,a+i);n.push(e.rel_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.rels;r.forEach(o=>{this.relations[o.uuid]=_(g({},o),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&await this.resolveLinks(e,t);for(const o in this.relations)this.iterateTree(this.relations[o],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(o=>{this.iterateTree(o,r)})}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(o,n)=>{let i=w({url:e,params:t}),a=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const c=await a.get(i);if(c)return o(c)}try{let c=await this.throttle("get",e,{params:t,paramsSerializer:k=>w(k)}),d={data:c.data,headers:c.headers};if(c.headers["per-page"]&&(d=Object.assign({},d,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return n(c);(d.data.story||d.data.stories)&&await this.resolveStories(d.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,d),d.data.cv&&(t.version=="draft"&&y[t.token]!=d.data.cv&&this.flushCache(),y[t.token]=d.data.cv),o(d)}catch(c){if(c.response&&c.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(u=1e3*r,new Promise(d=>setTimeout(d,u))),this.cacheResponse(e,t,r).then(o).catch(n);n(c)}var u})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get:e=>b[e],getAll:()=>b,set(e,t){b[e]=t},flush(){b={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}async flushCache(){return await this.cacheProvider().flush(),this}}var W=(s={})=>{const{apiOptions:e}=s;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new Q(e)}},X=s=>{if(typeof s!="object"||typeof s._editable=="undefined")return{};const e=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};const T=(s,e,t={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],o=>{o.action=="input"&&o.story.id===s?e(o.story):window.location.reload()})})}},Z=(s={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:o={}}=s;o.accessToken=o.accessToken||t;const n={bridge:e,apiOptions:o};let i={};return r.forEach(a=>{i=g(g({},i),a(n))}),e!==!1&&Y("https://app.storyblok.com/f/storyblok-v2-latest.js"),i},K=t=>{var r=t,{blok:s}=r,e=q(r,["blok"]);if(!s)return console.error("Please provide a 'blok' property to the StoryblokComponent"),E.default.createElement("div",null,"Please provide a blok property to the StoryblokComponent");const o=$(s.component);return o?E.default.createElement(o,N({blok:s},e)):""},ee=(s,e={},t={})=>{let[r,o]=h.useState({});return m?(T(r.id,n=>o(n),t),h.useEffect(async()=>{const{data:n}=await m.get(`cdn/stories/${s}`,e);o(n.story)},[]),r):(console.error("You can't use useStoryblok if you're not loading apiPlugin."),null)},te=(s={},e={})=>{let[t,r]=h.useState(s);return T(t.id,o=>r(o),e),h.useEffect(()=>{r(s)},[s]),t};let m=null;const re=()=>(m||console.error("You can't use useStoryblokApi if you're not loading apiPlugin."),m);let S={};const $=s=>S[s]?S[s]:(console.error(`Component ${s} doesn't exist.`),!1),oe=(s={})=>{const{storyblokApi:e}=Z(s);m=e,S=s.components};l.StoryblokComponent=K,l.apiPlugin=W,l.getComponent=$,l.storyblokEditable=X,l.storyblokInit=oe,l.useStoryblok=ee,l.useStoryblokApi=re,l.useStoryblokBridge=T,l.useStoryblokState=te,Object.defineProperties(l,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
@@ -496,9 +496,10 @@ const useStoryblok = (slug, apiOptions = {}, bridgeOptions = {}) => {
496
496
  };
497
497
  const useStoryblokState = (initialStory = {}, bridgeOptions = {}) => {
498
498
  let [story, setStory] = useState(initialStory);
499
+ useStoryblokBridge(story.id, (newStory) => setStory(newStory), bridgeOptions);
499
500
  useEffect(() => {
500
- useStoryblokBridge(story.id, (story2) => setStory(story2), bridgeOptions);
501
- }, []);
501
+ setStory(initialStory);
502
+ }, [initialStory]);
502
503
  return story;
503
504
  };
504
505
  let storyblokApiInstance = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/react",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "SDK to integrate Storyblok into your project using React.",
5
5
  "main": "./dist/storyblok-react.js",
6
6
  "module": "./dist/storyblok-react.mjs",