Step-by-step guide on fetching blog posts from a Ghost blog by utilizing the API in a Vue cli project

I'm currently working on my Vue cli project and I am trying to showcase all the posts from a Ghost blog using the API.

Unfortunately, the example provided on the page is for a nuxt project.

Once we have called the dependencies and authenticated with the blog, we can create a function to fetch the posts:

export async function getPosts() {
  return await api.posts
    .browse({
      limit: "all"
    })
    .catch(err => {
      console.error(err);
    });
}

Now, on the vue page:

<template>
  <ul>
    <li v-for="post in posts">{{ post.title }}</li>
  </ul>
</template>

<script>
  import { getPosts } from '../api/posts';

  export default {
    async asyncData () {
      const posts = await getPosts();
      return { posts: posts }
    }
  }
</script>

This setup works seamlessly on Nuxt as well as Node.

Simply calling the function gets us all the posts without any issues.

However, when attempting the same approach within the Data function in vue like this:

data: () => {
   let posts = getPosts()
   return {
    resultado: posts,
  };
}

The getPosts() function returns a pending Promise.

I've tried resolving the promise using .then() to access the results but faced difficulties passing it to the return part of data.

data: () => {
    let posts = getPosts()
      .then((results) => {
        return results;
      })
      .catch((err) => {
        console.error(err);
      });
    return {
      resultado: posts,
    };
  }

Any suggestions on how to make the results from getPosts() available on the template would be highly appreciated!

Thank you!

Answer №1

Instead of calling it directly, why not use a lifecycle hook:

data() {
  return {
    response: null
  }
},
async created() {  // or async mounted()
  this.response = await fetchData();
}

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

Is it possible to utilize PHP to dynamically add a URL, media, and description on Pinterest?

Check out this code snippet: <script type="text/javascript"> (function() { window.PinIt = window.PinIt || { loaded:false }; if (window.PinIt.loaded) return; window.PinIt.loaded = true; function async_load(){ var s = document.createElement("scrip ...

Unable to reach 'this' within a nested function

Struggling with a coding issue for hours now and in need of some assistance. The challenge at hand involves creating an object named Rank. Rank is expected to make DB calls in mongodb to retrieve data needed to populate a matrix, followed by executing nes ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...

What is the importance of having the same data type for the searchElement in the argument for Array.prototype.includes()?

Is there an issue with my settings or is this a feature of TypeScript? Consider the code snippet below: type AllowedChars = 'x' | 'y' | 'z'; const exampleArr: AllowedChars[] = ['x', 'y', 'z']; f ...

obtain a jQuery element from a function

Can a function return a $ object, or does it need to be converted to a string before being returned? function returnObj() { obj = $("<img id='' src='' />"); return obj; } var obj = returnObj(); alert(obj); //returns [obj ...

How to Send a JavaScript Array to a JSP Endpoint

I'm in the process of creating a web application that interacts with another website through a JS API. I would like to incorporate an array of JSON objects obtained from this API into my Java Application. Is there any way to submit this array, perhap ...

What is the mechanism behind angular2's spa routing functioning seamlessly without the need for the hash character in the url?

During my experience with the Angular2 "Tour of Heroes" tutorial, I made an interesting observation about how their single page application router functions without a trailing hash symbol (#) in the URL. This differs from the Kendo SPA router, which typica ...

Utilizing Jquery functions within the AngularJS framework

Utilizing Uikit along with its pagination feature, I am attempting to implement this function for changing the page: $('[data-uk-pagination]').on('uk-select-page', function(e, pageIndex){ console.log("page " + pageIndex); ...

What is preventing window.scrollTo() from being executed?

I have implemented Bootstrap's Buttons plugin to toggle the state of a custom checkbox. When the button is toggled on, a hidden element should appear at the top of the page and then the page should scroll to the top. Similarly, when the button is togg ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

Using javascript, retrieve the JSON values for each level

I need help using a recursive function in JavaScript to retrieve the last key value pair from a simple JSON object. Here is an example JSON object: { 'a': { 'b': { 'c': 12, 'd': 'Hello World& ...

Grid layout with card tiles similar to Google Plus

I'm looking to develop a scrolling grid with card tiles similar to Google Plus that has three columns. I am currently using Material UI, but I can't seem to find the right functionality for this. I have experimented with the standard Material UI ...

What is the best way to clear an arrayList when an error occurs in the ajax response?

Within my code, I have initialized an empty arrayList as var selection11Data = [];. Data is retrieved from an AJAX call as shown below: var selectionId=trData.selectionId; console.log("here"); $.ajax({ url : A_PAGE_ ...

The functionality of the jQuery click event is not functioning properly

I encountered a strange issue where the code below works perfectly fine when directly pasted into the browser (chrome console). However, it does not work when executed from my source file. <script type="text/javascript" > $(".test").click( ...

Adjust the size of the sliding tool with images of varying dimensions

My mobile-first slider features three different types of images: tall, horizontally long, and square. I want the size of the slider to be determined by the horizontally long image and then scale and center the other images to fit its size. To achieve this, ...

Provide a numerical representation of how frequently one object value is found within another object value

Account Object Example in the Accounts Array: const accounts = [ { id: "5f446f2ecfaf0310387c9603", picture: "https://api.adorable.io/avatars/75/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6b7d7a666 ...

Managing incoming HTTP requests on LoopBack can be easily done by following these steps

I am currently working with loopback to create a login page. The client-side files contain the code for the login page $(document).ready(function(){ $('#login').click(function(){ var username = $('#usr').val(); var password = ...

Harnessing the Power of Google Tag Script in Next.js

After researching How to load Google Tag Manager with the next/script component (Next.js 11) and reviewing this documentation page, my issue remains unresolved. I am looking to implement Google Tag on multiple websites developed using nextjs, so I created ...

To handle async actions in Typescript with React and Redux, ensure that all actions passed to axios are plain objects. If you need to perform

Looking for assistance with Typescript, React, and Redux. export function fetchAllMeals (subject: string){ axios .get(`https://www.themealdb.com/api/json/v1/1/search.php?s=${subject}`) .then((response: any) => { console.log(response.data) ...