storyblok / storyblok-nuxt

Storyblok Nuxt module
https://www.storyblok.com/tp/nuxt-js-multilanguage-website-tutorial
272 stars 42 forks source link

useAsyncStoryblok not fetching content in storyblok visual editor #841

Open Kiewiet1024 opened 4 months ago

Kiewiet1024 commented 4 months ago

Describe the issue you're facing

It would appear that there is a race condition in src/runtime/composables/useAsyncStoryblok.ts when using the visual editor in storyblok that leads to no data being received in time and throwing an error: Cannot read properties of undefined (reading 'id') since story is returning null in the following snippet:

onMounted(() => {
    if (story.value && story.value.id) {
      useStoryblokBridge(
        story.value.id,
        evStory => (story.value = evStory),
        bridgeOptions,
      );
    }
  });

  if (!story.value) {
    const { data } = await useAsyncData(uniqueKey, () => {
      return storyblokApiInstance.get(
        `cdn/stories/${url}`,
        apiOptions
      );
    })
    if(data) {
      story.value = data.value?.data.story
    }
  }
  return story

Reverting the above snippet to the one below resolves this

onMounted(() => {
    if (story.value && story.value.id) {
      useStoryblokBridge(
        story.value.id,
        evStory => (story.value = evStory),
        bridgeOptions,
      );
    }
  });

if (!story.value) {
    const { data } = await storyblokApiInstance.get(
      `cdn/stories/${url}`,
      apiOptions
    );
    story.value = data.story;
  };

return story;

Not sure if there are other changes regarding this that is needed to make it work.

Reproduction

https://storyblok.com

Steps to reproduce

Using the visual editor in storyblok will result in the error being thrown. Please note that it has to be used with the serving of the build files and not using npm run dev or yarn dev. Unfortunately I am not able to share the repository

System Info

System:
    OS: macOS 13.5
    CPU: (10) arm64 Apple M1 Pro
    Memory: 43.13 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.0 - ~/.nvm/versions/node/v20.11.0/bin/node
    Yarn: 1.22.19 - ~/dev/homebrew/bin/yarn
    npm: 10.5.1 - ~/.nvm/versions/node/v20.11.0/bin/npm
  Browsers:
    Chrome: 125.0.6422.112
    Safari: 16.6

Used Package Manager

yarn

Error logs (Optional)

No response

Validations