my first API request is always null with vue, nuxt3 and typescript

73 views Asked by At

I try to create a website with Vue3 javascript, typescript and nuxt.

i created a a composables to make request to my laravel API( i use breeze -api)

import type  {UseFetchOptions } from 'nuxt/app'

export function useApiFetch<T> (path: string, options: UseFetchOptions<T> = {}) {
  let headers: any = {}
  const token = useCookie("XSRF-TOKEN");

  if (token.value){
    headers["X-XSRF-TOKEN"] = token.value as string
  }

  if (process.server) {
    headers = {
      ...headers,
      ...useRequestHeaders(["referer", "cookie"])
    }
  }

  return useFetch("http://localhost:8000" + path, {
    credentials: "include",
    watch: false,
    ...options,
    headers: {
      ...headers,
      ...options?.headers
    }
  })
}

then i call it in my front with the function LoadDisplayCart in the useCartStore

<script setup lang="ts">
import { useCartStore } from '../stores/useCartStore';
import { storeToRefs } from 'pinia';
import { DisplayCart } from "../types/interfaces"
import { toast } from 'vue3-toastify';
import 'vue3-toastify/dist/index.css';

const cartStore = useCartStore()
const {cart, displayCart} = storeToRefs(cartStore)

onMounted(() => {
    cartStore.loadCartInstance();
    cartStore.loadDisplayCart();
});
.......
 async loadDisplayCart(){
            const productDetails = (this.cart as Cart).products.map(ci => ({id: ci.id, size_id: ci.size.id}));

            const a = await useApiFetch('/api/products', {
                method: 'POST',
                body: JSON.stringify(productDetails),
            })
            .then(response => {
                if (response.data) {
                    console.log("data",response.data)
                    const productsData = response.data.value as any[];
                    console.log("product", productsData)
                    this.displayCart = (this.cart as Cart).products.map(ci => {
                        console.log("ci" ,ci)
                        const products = productsData.find(p => p.id == ci.id && p.sizes[0].id == ci.size.id);
                        console.log(products)
                        return {
                            nom: products.title,
                            prix: products.sizes[0].pivot.price,
                            quantite: ci.quantite,
                            id: ci.id,
                            size: ci.size
                        };
                    });
                }
            })
            .catch(error => console.error('Error:', error));
        },

my console.log("product", productsData) give me a null value.

But when i reload the page doing ctrl+s in my IDE the website request go into API once more and then give the good result with good data associated.

It doesn't happen only here but for every request i make in the website.

Please help me!!

PS:Sorry for my english.... im not fluent

I tried to use the fetch method and not My useAPIFetch but same result

0

There are 0 answers