Last active
March 23, 2023 07:17
-
-
Save SebbeJohansson/34bc2cdf01d05b981baa418f04940876 to your computer and use it in GitHub Desktop.
Custom useAsyncStoryblok with proper error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useStoryblokApi, useStoryblokBridge } from "@storyblok/vue"; | |
import type { ISbStoriesParams, StoryblokBridgeConfigV2, ISbStoryData, ISbError, ISbResult } from '@storyblok/vue'; | |
export const useCustomAsyncStoryblok = async ( | |
url: string, | |
apiOptions: ISbStoriesParams = {}, | |
bridgeOptions: StoryblokBridgeConfigV2 = {}, | |
) => { | |
const uniqueKey = `${JSON.stringify(apiOptions)}${url}`; | |
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, | |
); | |
} | |
}); | |
const { data, error } = await useAsyncData<ISbResult, ISbError>( | |
`${uniqueKey}-asyncdata`, | |
() => storyblokApiInstance.get(`cdn/stories/${url}`, apiOptions), | |
); | |
if (error.value?.response && error.value?.response.status >= 400 && error.value?.response.status < 600) { | |
throw createError({ statusCode: error.value?.response.status, statusMessage: error.value?.message?.message || 'Something went wrong when fetching from storyblok.' }); | |
} | |
story.value = data.value?.data.story; | |
return story; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment