搜尋

首頁  >  問答  >  主體

未捕獲(承諾中)類型錯誤:X 不是函數

我正在嘗試建立一個 vue 應用程序,透過 Spotify 的 API 進行搜尋來尋找曲目。但我有一個問題,它說:

未捕獲(承諾中)類型錯誤:searchTracks 不是函數

每當我呼叫 searchTracks 函數時。我尋找解決方案,但似乎找不到。 我有在不同檔案 (useSpotify.js) 上存取 Spotify API 的程式碼(我仍在學習)

import { ref } from 'vue'

const useSpotify = async () => {
    let token
    const id = 'MyId'
    const secretId = 'mySecretId'

    const res = await fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + btoa(id + ':' + secretId)
        },
        body: 'grant_type=client_credentials'
    });

    token = await res.json();
    console.log(token);

    const searchTracks = async (searchTerm) => {
        console.log(token)
        const res = await fetch(`https://api.spotify.com/v1/search?${searchTerm}&type=track`, {
            method: 'GET',
            headers: { 'Authorization': 'Bearer ' + token }
        });
        const data = ref(null)
        data.value = await res.json()
        console.log(data.value)

        return data.value
    }

    return { searchTracks }
}

export default useSpotify

我在 vue 元件中呼叫它只是為了嘗試一下(Login.vue)您可以轉到 //searchTry 查看此嘗試完成的程式碼

<template>
  <form @submit.prevent="handleLoginSubmit">
    <h3>Login</h3>
    <input type="email" placeholder="Email" v-model="email" />
    <input type="password" placeholder="Password" v-model="password" />
    <div class="error" v-if="error">{{error}}</div>
    <button v-if="!isPending">Login</button>
    <button v-if="isPending" disabled>Loading..</button>
  </form>
  <input type="text" v-model="searchTerm">
  <button @click="search">search</button>
</template>

<script>
import useLogin from "@/composables/useLogin";
import { ref } from '@vue/reactivity';
import { useRouter } from 'vue-router';
// searchTry
import useSpotify from '../../composables/spotifyApi/useSpotify'
// searchTry
export default {
  setup() {
    const {error, isPending, login} = useLogin()
    const router = useRouter()

    const email = ref('')
    const password = ref('')

    const handleLoginSubmit = async () =>{
      const res = await login(email.value, password.value)
      if(!error.value){
        router.push({name: 'UserPlaylists'})
      }
    }
    // search try
    const searchTerm = ref('')
    const {searchTracks} = useSpotify()
    const search = async () =>{
      const res = searchTracks(searchTerm.value)
    }
    // search try

    return{email, password, isPending, error, handleLoginSubmit, searchTerm, search}
  },
};
</script>

<style>
我不明白問題來自哪裡。請幫忙(我還是不太擅長 JavaScript,請指出我所犯的錯誤)

P粉401527045P粉401527045249 天前436

全部回覆(1)我來回復

  • P粉427877676

    P粉4278776762024-03-22 11:20:26

    您將 useSpotify 定義為 async 函數,呼叫時應使用 awaitthen() 。非同步函數的回應始終是承諾。 文件

    useSpotify().then((result) => {
            const {searchTracks} = result
            // rest of your code
        })

    回覆
    0
  • 取消回覆