Skip to content

Commit

Permalink
Merge pull request #870 from yannic-wtfoxtrot/main
Browse files Browse the repository at this point in the history
fix: conditional hooks in useStoryblokState and useStoryblok
  • Loading branch information
fgiuliani authored Dec 13, 2023
2 parents 35398c0 + 0a1abcd commit d0f87c6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 24 deletions.
16 changes: 8 additions & 8 deletions lib/common/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,21 @@ export const useStoryblokState: TUseStoryblokState = (
const isBridgeEnable =
typeof window !== "undefined" &&
typeof window.storyblokRegisterEvent !== "undefined";

if (!isBridgeEnable || !initialStory) {
return initialStory;
}

const id = (story as any).internalId || story.id;


useEffect(() => {
if (!isBridgeEnable || !initialStory) return
const id = (story as any).internalId || story.id;
setStory(initialStory);
registerStoryblokBridge(
id,
(newStory) => setStory(newStory),
bridgeOptions
);
}, [initialStory]);
}, [initialStory, isBridgeEnable, story]);

if (!isBridgeEnable || !initialStory) {
return initialStory;
}

return story;
};
35 changes: 19 additions & 16 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,21 @@ export const useStoryblok = (
apiOptions: ISbStoriesParams = {},
bridgeOptions: StoryblokBridgeConfigV2 = {}
) => {
const storyblokApiInstance = getStoryblokApi();
if (!storyblokApiInstance) {
console.error(
"You can't use useStoryblok if you're not loading apiPlugin."
);

return null;
}

let [story, setStory] = useState<ISbStoryData>({} as ISbStoryData);

bridgeOptions.resolveRelations =
bridgeOptions.resolveRelations ?? apiOptions.resolve_relations;

bridgeOptions.resolveLinks =
bridgeOptions.resolveLinks ?? apiOptions.resolve_links;

const isBridgeEnable =
typeof window !== "undefined" &&
typeof window.storyblokRegisterEvent !== "undefined";

const storyblokApiInstance = getStoryblokApi();

useEffect(() => {
if (!storyblokApiInstance) {
console.error(
"You can't use useStoryblok if you're not loading apiPlugin."
);
return
}
async function initStory() {
const { data } = await storyblokApiInstance.get(
`cdn/stories/${slug}`,
Expand All @@ -54,7 +47,17 @@ export const useStoryblok = (
}

initStory();
}, [slug, JSON.stringify(apiOptions)]);
}, [slug, JSON.stringify(apiOptions), storyblokApiInstance]);

if (!storyblokApiInstance) {
return null;
}

bridgeOptions.resolveRelations =
bridgeOptions.resolveRelations ?? apiOptions.resolve_relations;

bridgeOptions.resolveLinks =
bridgeOptions.resolveLinks ?? apiOptions.resolve_links;

return story;
};
Expand Down

0 comments on commit d0f87c6

Please sign in to comment.