Laravel Türkiye Discord Kanalı Forumda kod paylaşılırken dikkat edilmesi gerekenler!Birlikte proje geliştirmek ister misiniz?

server/api/user/login.ts

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const user = await $fetch('http://localhost:5000/api/v1/auth/login', {
      method: 'POST',
      body,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    return user;
  } catch (error) {
    console.error('Error at getting user:', error);
    throw createError({ statusCode: 500, message: 'Internal Server Error' });    
  }
})

authStore

import { defineStore } from 'pinia'
import { useFetch } from '#app' // Nuxt3 ile gelen useFetch fonksiyonu

export const useAuthStore = defineStore({
  id: 'AuthStore',
  state: () => ({
    user: null
  }),
  actions: {
    async register(newUser) {
      try {
        const { data, error } = await useFetch('/api/user/register', {
          method: 'POST',
          body: JSON.stringify(newUser),
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (error.value) {
          console.error('Error fetching data:', error.value.message);
        } else {
          console.log(data.value, 'data');
          this.user = data.value;
        }
      } catch (error) {
        console.error('Error in register action:', error);
      }
    },
    async login(newUser) {
      try {
        const { data, error } = await $fetch('/api/user/login', {
          method: 'POST',
          body: JSON.stringify(newUser),
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        if (error.value) {
          console.error('Error fetching data:', error.value.message);
        } else {
          console.log(data.value, 'data');
          this.user = data.value;
        }
      } catch (error) {
        console.error('Error in register action:', error);
      }
    }
  }
});

login.vue

<script setup>
import { useAuthStore } from "~/store/authStore";

const authStore = useAuthStore();

const formData = reactive({
  email: "",
  password: "",
});

const submitForm = async () => {
  try {
    await authStore.login(formData);
    console.log("Login successful");
  } catch (error) {
    console.error("Login failed:", error);
  }
};
</script>

kodlarım şöyle ve çalışıyor fakat bana

[nuxt] [useFetch] Component is already mounted, please use $fetch instead. See https://nuxt.com/docs/getting-started/data-fetching

diyor ve ben bunu araştırdım
https://github.com/nuxt/nuxt/discussions/25602
buraya baktım adamın videosunu izledim fakat anlamadım tam olarak.
Bu tartışmada verilen bir cevap:

If you need the data for hydration, useFetch / useAsyncData is the way!
When sending e.g. a form or respond to a button click, $fetch is the way to go.
See also approach 2 in the video, where you can use useFetch for both by defining it "earlier"/"top-level" ☺️

Bu tartışmada sorulan bir soru:

I use useFetch in my pinia stores... and I get this warning.
Does that mean I'm supposed to use $fetch instead always? My pinia stores are isolated and I've watched the video of the issues with using useFetch in different scenarios, but none of those negative affects happen to me. Pinia is probably protecting me from some of those negative side affects, but this warning is still there. It's a huge project so I'm not looking forward to refactoring all the useFetch calls.

Ayrıca chatgptye sorduğumda bana

useFetch ve $fetch Nedir?
$fetch: Bu, sunucu tarafında veri çekmek için kullanılan bir fonksiyondur ve genellikle Nuxt.js 3'ün backend işlevlerinde veya API isteklerinde kullanılır. Sunucu tarafında çalışırken, doğrudan veri çekmek ve işlemek için bu yöntemi kullanırsınız. Bu, özellikle API handler'larında ve sunucu tarafı işlemlerinde kullanılır.

useFetch: Bu, Vue bileşenlerinde veri çekmek için kullanılan bir fonksiyondur ve genellikle bileşenlerin içinde veya sayfa içinde veri getirmek için kullanılır. Bu metod, bileşenlerin yaşam döngüsüne bağlı olarak veri çekme işlevselliği sağlar ve bileşenin mount (monte) olma durumuna göre davranır.

Nerede Kullanılmalı?
$fetch: Sunucu tarafında veri almak veya POST istekleri yapmak için kullanılır. API endpoint'leri ve server-side kodlarda kullanılır. Örneğin, Nuxt.js 3'ün API handler'larında veya middleware'de $fetch kullanılır.

useFetch: Vue bileşenlerinde, sayfa veya bileşen içi veri çekme işlemleri için kullanılır. Bu, bileşenlerin render edilmesi sırasında veya sayfanın yüklenmesi sırasında veri getirmek için uygundur.

diyor fakat öyleyse warning vermemesi gerek.

Bilgisi olan varsa detaylı şekilde açıklayabilir mi.

async login(newUser) {
      try {
        const data = await $fetch('/api/user/login', {
          method: 'POST',
          body: JSON.stringify(newUser),
          headers: {
            'Content-Type': 'application/json'
          }
        });

        this.user = data;
        console.log(data);
        
        
        // if (error.value) {
        //   console.error('Error fetching data:', error.value.message);
        // } else {
        //   console.log(data.value, 'data');
        //   this.user = data.value;
        // }
      } catch (error) {
        console.error('Error in register action:', error);
      }
    }

kodu böyle yaptığımda yani useFetch yerine $fetch kullandığımda warning mesajı gelmiyor. Fakat daha fazla bilgiye sahip olmak için sorayım dedim.

  • mgsmus bunu yanıtladı.
  • aghabalaguluzade Aslında videoda anlatmış. useFetch refleri takip ediyor, değiştiğinde tekrar istek atıyor, yanıtı reactive dönüyor, component yaşam döngüsünü takip ediyor vs. $fetch ise klasik XmlHttpRequest. Mesela useFetch etkisini $fetch ile nasıl yaparım diye düşünürseniz bir watcher içinde $fetch yaptığınızı düşünebilirsiniz. Sadece ben istediğimde istek atsın, benden bağımsız bir şey yapmasın diyorsanız ve axios kullanmıyorum diyorsanız $fetch kullanacaksınız.

    Usefetch , nuxt a özeldir. Veritabanından veri getirmek için kullanılır. Bir login veya register için kullanılması önerilmez, bunun için $fetch veya axios kullanmalısınız.
    nuxt3 resmi sitesinde data fetching başlığı altında aşağıdaki Alexander Lichter in videosunu izlemeniz önerilir.
    https://www.youtube.com/watch?v=njsGVmcWviY
    usefetch ve $fetch hakkında aşağıdaki Abdullah hocanın videosunu izlemenizi öneririm, çok güzel anlatmış.
    https://www.youtube.com/watch?v=KPiEbGeQ_q8&list=PLf-6qk7szL-JUalfdUEqHeLnCTXi0DNB9&index=6

    aghabalaguluzade Aslında videoda anlatmış. useFetch refleri takip ediyor, değiştiğinde tekrar istek atıyor, yanıtı reactive dönüyor, component yaşam döngüsünü takip ediyor vs. $fetch ise klasik XmlHttpRequest. Mesela useFetch etkisini $fetch ile nasıl yaparım diye düşünürseniz bir watcher içinde $fetch yaptığınızı düşünebilirsiniz. Sadece ben istediğimde istek atsın, benden bağımsız bir şey yapmasın diyorsanız ve axios kullanmıyorum diyorsanız $fetch kullanacaksınız.