简体   繁体   中英

Why can't I fetch and display data from this API in Nuxt 3?

I've followed many examples online on how to fetch a list of names from an API in Nuxt 3 such as the following and they always work as expected but have had no luck replicating the same results for a particular API that I need to use.

<template>
    <ul>
      <li v-for="user in users" :key="user.id">
        {{ user.name }}
      </li>
    </ul>
</template>
<script setup>
  const { data : users } = await useFetch('https://jsonplaceholder.typicode.com/users')
</script>

Here is the API I've tried to use following the above example without success. It contains a list of stores listed here as shops here. https://mocki.io/v1/3fa1924f-6c6b-4d49-b9ec-d91f6da13c3c

As you see here on Stackblitz it works fine. https://stackblitz.com/edit/github-hk8kro?file=pages/index.vue

I assumed that the following code would work but I get an error saying 500 Cannot read properties of null (reading 'name') as you can see here as well in Stackblitz. https://stackblitz.com/github/mike-420/fetchingdata2?file=README.md

<template>
    <ul>
      <li v-for="shop in shops" :key="shop.id">
        {{ shop.name }}
      </li>
    </ul>
</template>
<script setup>
  const { data : shops } = await useFetch('https://mocki.io/v1/3fa1924f-6c6b-4d49-b9ec-d91f6da13c3c')
</script>

Any suggestions anyone please?

500 is just a generic something went wrong on the server error, and because this HTML is being rendered on the server, it's producing that error code.

The issue is asynchronous JS. Before you've retrieved the stores data from the API, you are attempting to render data that has not made its way to your server yet. So according to your app, shop.name does not exist when it attempts to render.

There are many ways to deal with this issue.

For example you can either wrap that block of code in a v-if statement that checks if the stores object is empty.

Or you can implement optional chaining in your template to render some placeholder text.

In script setup use:

const shops = ref()
const { data : shopsData } = await useFetch('https://mocki.io/v1/3fa1924f-6c6b-4d49-b9ec-d91f6da13c3c')
shops.value = shopsData.value.data.shops

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM