简体   繁体   中英

Working with promises in a React class component

I have this module to fetch data using the Spotify API:

const Spotify = {
  getAccessToken() { ... },

  searchTrack(searchTerm) {
    const accessToken = Spotify.getAccessToken();

    return fetch(
      `https://api.spotify.com/v1/search?q=${searchTerm}&type=track`,
      {
        headers: { Authorization: `Bearer ${accessToken}` },
      }
    )
      .then((response) => response.json())
      .then((jsonResponse) => jsonResponse.tracks.items[3].name);
  },
};

I then import it to this class component and try to display the data:

  termToSearch() {
     return(Spotify.searchTrack(this.props.searchTerm))

}

But I keep getting this error:

Uncaught Error: Objects are not valid as a React child (found: [object Promise])... 

Also, when I alternately try to set the state in the function, I get an infinite loop of calls to the fetch API. I'm now really stuck on how to render this returned data.

If I understood correctly, you are trying to return the response getting from the fetch API call. Fetch will always return a promise and that is the reason you are getting Uncaught Error: Objects are not valid as a React child (found: [object Promise])...

You can use async and await to the function so that the promise will be resolved and return the result.

 async function fetchAPI() { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const result = await response.json(); return result; } catch (error) { console.error(error); } } async function api() { const result = await fetchAPI(); console.log(result); } api();

I think you can change your method to something like this.

async searchTrack(searchTerm) {
    let res; 
    const accessToken = Spotify.getAccessToken();
    const data = await fetch(`https://api.spotify.com/v1/search?q=${searchTerm}&type=track`, {
        headers: { Authorization: `Bearer ${accessToken}` }
    });
    const jsonResponse = await data.json();
    return jsonResponse.tracks.items[3].name;
}

When you are calling the method you need to add await

async termToSearch() {
     return(await Spotify.searchTrack(this.props.searchTerm))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM