Skip to content

Instantly share code, notes, and snippets.

@SebbeJohansson
Last active January 28, 2023 19:00
Show Gist options
  • Save SebbeJohansson/b1f6bf3df13cd1d9cbf6a02f8cb2297f to your computer and use it in GitHub Desktop.
Save SebbeJohansson/b1f6bf3df13cd1d9cbf6a02f8cb2297f to your computer and use it in GitHub Desktop.
Custom useAsyncStoryblok function with proper error handling
<!-- Example page -->
<script setup lang="ts">
import { ISbStoryData } from '@storyblok/vue/dist';
const route = useRoute();
const { locale } = useI18n();
let story = {} as ISbStoryData;
try {
const currentRoute = { ...route };
const localeString = `/${locale.value}`;
if (currentRoute.path.startsWith(localeString)) {
currentRoute.path = currentRoute.path.slice(localeString.length);
}
if (currentRoute.path === '/') {
currentRoute.path = 'home';
}
currentRoute.path = currentRoute.path.replace(/(^\/+|\/+$)/mg, '');
const isPreview = !!(currentRoute.query._storyblok && currentRoute.query._storyblok !== '');
const version = isPreview ? 'draft' : 'published';
await useCustomAsyncStoryblok(currentRoute.path, {
version,
language: locale.value,
resolve_relations: 'popular-articles.articles',
}, {
preventClicks: true,
}).then((res) => {
if (res) {
story = res.value;
}
});
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
</script>
<template>
<StoryblokComponent v-if="story.content" :blok="story.content" />
</template>
import { useStoryblokApi, useStoryblokBridge } from '@storyblok/vue';
// https://github.com/storyblok/storyblok-nuxt/pull/280
import type { ISbStoryData, ISbError, ISbResult } from '@storyblok/vue';
export const useCustomAsyncStoryblok = async (
url: string,
apiOptions = {},
bridgeOptions = {},
) => {
const uniqueKey = `${JSON.stringify(apiOptions)}${url}`;
// https://github.com/storyblok/storyblok-nuxt/pull/280
const story = useState<ISbStoryData>(`${uniqueKey}-state`, () => ({} as ISbStoryData));
const storyblokApiInstance = useStoryblokApi();
onMounted(() => {
if (story.value && story.value.id) {
useStoryblokBridge(
story.value.id,
evStory => (story.value = evStory),
bridgeOptions,
);
}
});
await useAsyncData<ISbResult, ISbError>(
`${uniqueKey}-asyncdata`,
async () => await storyblokApiInstance.get(`cdn/stories/${url}`, apiOptions),
).then((response) => {
const { data, error } = response;
const storyblokData = data.value as ISbResult;
const storyblokError = error.value as ISbError;
if (storyblokError) {
if (storyblokError.response.status >= 400 && storyblokError.response.status < 600) {
throw new Error(storyblokError.message.message);
}
}
story.value = storyblokData.data.story;
}).catch((error) => {
console.error('error', error);
});
return story;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment