Error: X does not conform to function definition

I'm currently in the process of developing a Vue application that interacts with Spotify's API to search for tracks. However, I've encountered an issue where I receive the following error message:

Uncaught (in promise) TypeError: searchTracks is not a function

Every time I attempt to call the searchTracks function. Despite my efforts to find a solution, I haven't been successful. I have the code for accessing Spotify's API in a separate file called useSpotify.js

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

Inside the vue component (Login.vue), I'm attempting to integrate it just to test it out. You can refer to //searchTry to view the coding done for this attempt

<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>
I am struggling to pinpoint the source of the problem. Any assistance would be greatly appreciated as I continue to learn and navigate through JavaScript.

Answer №1

If you have defined the function useSpotify as async, make sure to utilize await or then() when calling it. Async functions always return a promise. Check out the documentation for more information.

    useSpotify().then((result) => {
        const {searchTracks} = result
        // Add your additional code here
    })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure that my theme button changer has an impact on all pages throughout my website, not only on the

Looking for some help here - I've got a button that changes the theme/colour of my website, but it only seems to work on the homepage and not on any other pages. Anyone know how I can fix this issue? Here's the JavaScript code: $(document).ready ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

Retrieving an assortment of objects from a database and showcasing them using React

Attempting to retrieve an array of objects led me to this issue. Please excuse the messy code, I am still learning. export class App extends Component { state ={ character:[] } componentDidMount(){ fetch('https://swapi.dev/api/people/ ...

Eliminating pins from Biostall Google Maps plugin in CodeIgniter

After successfully setting up the Biostall Google Maps for Codeigniter, I am now looking to remove specific markers using ajax. The JavaScript code being executed is as follows: var myLatlng = new google.maps.LatLng(53.236114, 6.496444); var markerOption ...

Exploring nested hash maps within JavaScript

Having some trouble with creating a nested hash map in JavaScript (js), similar to the example below: let rooms = {}; rooms[roomNum][personName] = somethings; However, I keep encountering an error when attempting this: TypeError: Cannot set property &apo ...

While attempting to retrieve images from S3 using the AWS-SDK Nodejs, users may experience issues with downloading

My goal is to retrieve images from AWS S3 using the AWS-SDK for Node.js. Although the file is successfully downloaded and its size appears correct, it seems to be corrupted and displays a Decompression error in IDAT. async download(accessKeyId, secretAcce ...

Retrieve items from a JSON file using Ionic framework's $http.get method

Issue with Console: SyntaxError: Unexpected token { in JSON at position 119 Xcode controller: str="http://www.website.com/user-orders.php?e="+$scope.useremail; $http.get(str) .success(function (response){ $scope.user_orders = response; ses ...

The Angular service/value is failing to retrieve the updated variable from the $(document).ready() function

Currently, I'm facing an issue with my Angular service/value. It seems to be grabbing the original variable instead of the new one that is supposed to be inside $(document).ready(). Here's the relevant code snippet: var app = angular.module("app ...

Send a pair of values using a set of two parameters

My current code is currently passing only one parameter value. However, I would like to modify it to pass two values with two parameters. This is my current code: <script> function getfilter(str){ document.getElementById("result"). ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Inject SCSS variables into Typescript in Vue 2 Using Vue-cli 5

When working on my Vue 2 project (created using the Vue-cli v4), I successfully imported variables from my SCSS file into my typescript (.vue files) without any issues. I had the :export { ... } in my SCSS file _variables.scss, along with shims.scss.d.ts ...

The Facebook messenger checkbox plugin does not appear to be displaying correctly

I have integrated the Facebook Messenger Checkbox Plugin into my AngularJS application by following the guide provided at this link. Initially, I was able to successfully display the messenger checkbox plugin on a page. However, upon navigating to another ...

What is the best way to send information using an array of objects?

In my Angular 5 project, I am using the ngx select dropdown package (https://www.npmjs.com/package/ngx-select-dropdown) and I'm wondering how to pass an array of objects instead of an array of strings. Currently, when I do so, it displays [Object Obje ...

Implementing data updates in Ruby on Rails through AJAX or jQuery

Within a text field input lies the value of a database attribute (ref). Upon focusing on the field, a border appears and disappears upon clicking out. My dilemma is that I wish for the data within the text field to be saved in the database without the nee ...

Having trouble retrieving information using JSON from openweather.com

Currently, I am facing an issue while attempting to retrieve weather information from the openweather.com API using geo-location (latitude and longitude) data. Despite my efforts, I cannot seem to figure out why the data is not being retrieved successfully ...

attack using JavaScript, AJAX, and PHP from a remote location

One vulnerability of using Javascript is that it's a client-side language, making scripts accessible for reading and copying. Let's take a look at this code snippet as an example: <html> <head> <title>title</title> <s ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...

How can I iterate through each element of MySelector in the callback function of jquery-ui's draggable function?

When using: jQuery(MySelector).dragabble( start: function( e, ui ) { } ) In the start function: The start event provides $(this) with the current dragged element from MySelector. How can I loop through each element in MySelector to apply additional code ...

Tips for recognizing a functional component using vue-eslint-parser

Currently, I am in the process of developing my own eslint rule using vue-eslint-parser. One key requirement is to disallow functional components from utilizing Vue's template syntax. I have successfully created a rule that prohibits the usage of < ...

Enhancing x-axis presentation in D3.js-generated charts

I created a bar chart using D3.js, but I have encountered an issue with one of the values on the x-axis being too long. I attempted to use CSS properties like text-overflow: ellipsis, width: 10px, and overflow: hidden to abbreviate values that exceed a cer ...