Nuxt 3 - useFetch composable issue

103 Views Asked by At

Just learning Nuxt 3 and for the life of me can't see what I am doing wrong

I have an API endpoint at /api/cars/city that returns my data (With a couple of optional filters), that all works fine

I created a composable called useFetchCars.js to get the data from the API but it just errors saying it can't get the data, can anyone tell me why this is happening please as it looks correct to me?

export default async (city, filters) => {
    const {data, error} = await useFetch(`/api/cars/${city}`, {
        params: {
            ...filters,
        }
    });

    if(error) {
        throw createError({
            ...error.value,
            statusMessage: "Unable to fetch cars",
        })
    };

    return data;
};

my page is

<script setup>
  const route = useRoute();
  const cars = await useFetchCars(route.params.city, {
    minPrice: route.query.minPrice,
    maxPrice: route.query.maxPrice,
    make: route.params.make
  })

</script>

<template>
  <div>
    {{ cars }}
    <CarCards />
  </div>
</template>

Many Thanks

1

There are 1 best solutions below

0
On

Realised there was an error in my if error statement,

below works if others have something similar

export default async (city, filters) => {
    const {data, error} = await useFetch(`/api/cars/${city}`, {
        params: {
            ...filters,
        }
    });

    if(error.value){
        throw createError({
            ...error.value,
            statusMessage: "Unable to fetch cars",
        })
    };

    return data;
};