The fetch function yields an unresolved `[object Response]` result

I am attempting to retrieve the most recent blog posts from Hubspot through their API, which requires accessing 2 endpoints (one for the blog posts and one for the tag information associated with each post).

The initial call fetches the latest blog posts. Then, for each post, I need to fetch the tag information related to that post.

Below is the code that implements the process described above:

async getBlogs(contentGroupID: string = null, limit: number = null) {
    this.url = 'https://api.hubapi.com/cms/v3/blogs/posts?state=PUBLISHED&sort=-publish_date';

    const posts = await useFetch(
      this.url 
      + '&hapikey=' + this.HS_API_KEY
      + (contentGroupID ? '&content_group_id=' + contentGroupID : null)
      + (limit ? '&limit=' + limit : null)
    ).then(response => {
      return response;
    });

    const tags = (posts.data.value as any).results.map(post => fetch(`https://api.hubapi.com/blogs/v3/topics/${post.tagIds[0]+'?hapikey='+this.HS_API_KEY}`));
    const taggs = await Promise.all(tags);

    const payload = new Object();

    payload['blogPosts'] = posts;
    payload['tags'] = taggs;

    return payload;
}

Here is the browser response:

https://i.sstatic.net/IaBba.png

In the screenshot above, the blogPosts object resolves successfully, but the part with Promise.all() to retrieve the tagIds[0] does not. It returns [object Response].

I have attempted various methods to resolve this issue, but it always returns the unresolved Promise object. What is the correct approach to handle this and obtain the actual data?

As an example of what the tag data object should look like, here is the data for the tag with id 41520763199:

{
    "categoryId": 3,
    "contentIds": [],
    "created": 1613125431347,
    "deletedAt": 0,
    "description": "",
    "id": 41520763199,
    "language": "en-us",
    "name": "Case Studies",
    "portalId": 2734675,
    "slug": "case-studies",
    "translations": {},
    "updated": 1616091635999
}

Answer №1

Instead of returning a promise, it resolves to a Response object according to the fetchAPI resource

A helpful method is Response.json, which returns a promise that resolves by parsing the response body text as JSON

For example:

const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')

will give you a Response object.

 Response {type: 'basic', url: 'https://jsonplaceholder.typicode.com/todos/1', redirected: false, status: 200, ok: true, …}

Now if you do:

const json = await response.json()

You will get your actual response in json format:

{userId: 1, id: 1, title: 'delectus aut autem', completed: false}

Answer №2

When using the fetch function, it will return a Promise<Response>. In order to retrieve the result as a JavaScript object from a JSON string, you must use the .json() method on the response object. This can be done within a .then callback to avoid having to write multiple awaits.</p>
<pre class="language-javascript"><code>This async function getBlogs(contentGroupID = null, limit = null) {
    this.url = 'https://api.hubapi.com/cms/v3/blogs/posts?state=PUBLISHED&sort=-publish_date';
    
    const blogPosts = await useFetch(
      this.url 
      + '&hapikey=' + this.HS_API_KEY
      + (contentGroupID ? '&content_group_id=' + contentGroupID : '')
      + (limit ? '&limit=' + limit : '')
    );

    const tagPromises = posts.data.value.results.map(post => fetch(`https://api.hubapi.com/blogs/v3/topics/${post.tagIds[0]+'?hapikey='+this.HS_API_KEY}`).then(r => r.json()));

    const tags = await Promise.all(tagPromises);

    return {
        blogPosts,
        tags
    };
}

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

How can I access DOM elements in Angular using a function similar to the `link` function?

One way to utilize the link attribute on Angular 2 directives is by setting callbacks that can transform the DOM. A practical example of this is crafting directives for D3.js graphs, showcased in this pen: https://i.sstatic.net/8Zdta.png The link attrib ...

Is there a problem with handling custom images in Next.js and TypeScript with React Quill?

I am currently facing challenges with integrating react-quill into my TypeScript Next.js project. Specifically, I am encountering issues related to typing and handling ref. Any assistance in resolving these problems would be greatly appreciated. Below is ...

D3 event: Latest in Type Definitions for Version 6 and Beyond

I have a collection of widgets created using d3 (version 5) and now I need to transition them to version 7. After consulting the migration guide at , I discovered the updated syntax for events: // previously element.on('click', (d, i, e) => .. ...

What is the best way to enforce input requirements in Typescript?

I am currently facing an issue with two required inputs that need to be filled in order to enable the "Add" button functionality. I have considered using *ngIf to control the visibility of the button based on input values, but it seems to not be working. ...

Dealing with promise errors in ES6 - How to manage errors effectively

I have a simple code snippet that I've been working on: return Location.findById(locationId) .then(doc => { if(doc) { console.log('Found a matching record.....proceed to delete'); return Location.remove({_id: locationId ...

Using Bootstrap 4 with Angular 2: A Beginner's Guide

Currently, I am in the process of developing an Angular 2 application using TypeScript. My goal is to integrate the Bootstrap 4 framework with some custom theming. Is this achievable? I have encountered issues with the "ng2-bootstrap" npm package, as it d ...

Limit the utilization of toString through a TypeScript interface or type

Here's the interface I'm aiming for: export interface Point { readonly x: number; readonly y: number; readonly toString: never; } I initially expected it to function this way: const p: Point = {x: 4, y: 5}; // This should work fine p.toStr ...

Error involving key mismatch between TypeScript inherited interface and literal string type

There are 3 interfaces (A, B, and C) that all extend from a shared interface (Common). Additionally, there is a container type which holds arrays of these 3 interfaces (Container). The goal is to select one of the arrays and extract a common property from ...

What could be causing the rapid breakage of the socket in Ionic 3's Bluetooth Serial after just a short period

Although the code appears to be functioning correctly, it loses connection shortly after establishing it. This snippet contains the relevant code: import { Component } from '@angular/core'; import { Platform, NavController, ToastController, Ref ...

The second generic argument's inference is not limited

Seeking assistance in creating a function that allows for specifying objects which extend the type Record<string, Record<string, number>>, along with default values for certain properties within those objects. For instance, given specific inpu ...

Typescript constructor that accepts an object as an argument instead of traditional parameters

My constructor is becoming lengthy and not structured the way I would prefer. I am looking to pass an object to my constructor so that I can access fields by their names. Here is how the class looks currently. export class Group { id: string; constru ...

"Unable to select all items in Mat-Selection-List with the selectAll()

I am encountering an issue while trying to incorporate selectAll() and deselectAll() functions. The error message that I am receiving can be viewed here. My implementation involves a template-driven form, and below is the snippet of my code: <mat-sele ...

Utilizing async/await in React Redux for geolocation functionality

While attempting to retrieve the lng and lat by using geolocation with async and await, I encountered a situation where the promise was not awaited before it was passed to the reducer. Instead, another promise was returned. I had hoped that by using await ...

Does sharing values between different pages happen when we are utilizing Nuxt alongside Vuex Store?

Is it possible to share values between different pages using Vuex Store? We attempted to do so, but encountered an issue. While State returned the correct value on the same page, it was not set on different pages. Are we missing something in our implement ...

Circular referencing in Angular models causes interdependence and can lead to dependency

I'm facing a dependency issue with the models relation in my Angular project. It seems to be an architecture problem, but I'm not sure. I have a User model that contains Books, and a Book model that contains Users. When I run this code, I encoun ...

Top-notch approach for consolidating Typescript Declaration files into a single comprehensive file

Is there any efficient way to package declaration files together without using the module declaration approach? declare module "path/to/file" { ... } declare module "path/to/file/sub/file" { ... } and so on. I have encountere ...

Combine the remaining bars by stacking the highest one on top in Highchart

Making use of stacking to display the highest value as the longest column/bar, with smaller values being merged within the highest one, can create a more visually appealing stack chart. For example, when looking at Arsenal with values of 14 and 3, ideally ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Is it possible that jest is unable to catch the exception?

I have a simple function that looks like this: function foo({ platform }) { if (platform === 'all') { throw new Error('Platform value can only be android or ios'); } return `${platform}`; } After writing unit tests, the re ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...