-
Notifications
You must be signed in to change notification settings - Fork 36
/
index.ts
112 lines (87 loc) · 2.51 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { useState, useEffect } from "react";
import {
registerStoryblokBridge as registerSbBridge,
storyblokInit as sbInit,
} from "@storyblok/js";
import {
SbReactComponentsMap,
SbReactSDKOptions,
StoriesParams,
StoryblokBridgeConfigV2,
StoryblokClient,
StoryData,
} from "./types";
export { default as StoryblokComponent } from "./components/storyblok-component";
export {
storyblokEditable,
apiPlugin,
useStoryblokBridge,
registerStoryblokBridge,
renderRichText,
RichTextSchema,
} from "@storyblok/js";
export const useStoryblok = (
slug: string,
apiOptions: StoriesParams = {},
bridgeOptions: StoryblokBridgeConfigV2 = {}
) => {
let [story, setStory] = useState<StoryData>({} as StoryData);
if (!storyblokApiInstance) {
console.error(
"You can't use useStoryblok if you're not loading apiPlugin."
);
return null;
}
registerSbBridge(story.id, (story) => setStory(story), bridgeOptions);
useEffect(() => {
async function fetchData() {
const { data } = await storyblokApiInstance.get(
`cdn/stories/${slug}`,
apiOptions
);
setStory(data.story);
}
fetchData();
}, [slug]);
return story;
};
export const useStoryblokState = <T = void>(
initialStory: StoryData<T> = {} as StoryData<T>,
bridgeOptions: StoryblokBridgeConfigV2 = {},
preview: boolean = true
): StoryData<T> => {
let [story, setStory] = useState<StoryData<T>>(initialStory);
if (!preview) {
return initialStory;
}
useEffect(() => {
registerSbBridge(story.id, (newStory) => setStory(newStory), bridgeOptions);
setStory(initialStory);
}, [initialStory]);
return story;
};
let storyblokApiInstance: StoryblokClient = null;
export const useStoryblokApi = (): StoryblokClient => {
if (!storyblokApiInstance) {
console.error(
"You can't use getStoryblokApi if you're not loading apiPlugin."
);
}
return storyblokApiInstance;
};
export { useStoryblokApi as getStoryblokApi };
let componentsMap: SbReactComponentsMap = {};
export const getComponent = (componentKey: string) => {
if (!componentsMap[componentKey]) {
console.error(`Component ${componentKey} doesn't exist.`);
return false;
}
return componentsMap[componentKey];
};
export const storyblokInit = (pluginOptions: SbReactSDKOptions = {}) => {
const { storyblokApi } = sbInit(pluginOptions);
storyblokApiInstance = storyblokApi;
componentsMap = pluginOptions.components;
};
// Reexport all types so users can have access to them
export * from "./types";