The result from Axios yields an [object Promise]

Utilizing the Flickr API, I am receiving feed images from their platform.

In my Vue application, I have a computed property called filteredImages:

computed: {
filteredImages: async function() {
  return axios.get('https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=' + this.search + '&nojsoncallback=1')
  .then(function (response) {
    return response.data.items;
  })
}

},

When I use a console log to check the response.data.items, it correctly shows the expected result set. However, when I try to display it in HTML, it shows as [object Promise].

For a demonstration, feel free to view this Pen.

Any insights on why this might be happening?

Answer №1

When dealing with computed props, it's important to note that they do not work well with async functions. Instead, they depend on other reactive props to calculate them when needed. Therefore, the best approach is to call the async function whenever you require filtered images and then store the results in a reactive property within the data section.

Answer №2

One way to fetch data from an HTTP call and display it in the DOM is by following this example

new Vue({
    el: "#app",
    data: {
        search: "",
        filteredImages: "",
    },
    watch: {
        search: function (newVal, oldVal) {
            this.getItems();
        },
    },
    methods: {
        getItems: async function () {
            try {
                const { data } = await axios.get(
                    `https://api.flickr.com/services/feeds/photos_public.gne?format=jsonp&tags=${this.search}&nojsoncallback=1`
                );

                this.filteredImages = JSON.stringify(data.items)
            } catch (error) {
                console.error(error);
                this.filteredImages = error.toString();
            }
        },
    },
});

However, there is a reported issue with flickr using JSONP which axios or fetch do not support

To handle this, you can use the JSONP module

Answer №3

To optimize this process, consider placing the results of your computed function in the mounted section. Instead of using return response.data.items, try storing the data in a variable like so:

data() {
    return {
        items: null,
    }
},
mounted:{
    let vm = this;
    axios.get('https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=' 
    + this.search + '&nojsoncallback=1')
      .then(function (response) {
            vm.items = response.data.items;
      })
 }

Now, you can easily access items in your HTML once it's loaded and ready for display.

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

Transforming the string attribute of an object within a JavaScript array through mapping

Here is an array of objects: { "attr1": 123, "attr2": "a.end", }, { "attr1": 123, "attr2": "b.start", } The task is to remove the first part of the attr2 string up to and including the '.& ...

JavaScript incorporates input range sliding, causing a freeze when the mouse slides rapidly

Currently working on a custom slider and encountering an issue. When quickly moving the mouse outside the slider's range horizontally, exceeding its width, the slider doesn't smoothly transition to minimum or maximum values. Instead, there seems ...

The error message "app.use() function requires middleware function" appears when the app

Currently, I am in the process of learning node.js with express template engine by following a Udemy course called "Learn Node.js by Building 10 Projects". During one of the lectures, when the professor ran npm start localhost:3000, it worked fine for him, ...

What is the solution for changing image sources dynamically in React-Native?

How can I access image sources from a JSON file without encountering a module error when using JSON objects as the source? JSON FILE: { "Image": {"source": "./SourceFolder/ImageFile.png"} } JS FILE const data = require('./jason.json'); ...

Hiding Bootstrap Popover When User Clicks Outside of it

My webpage has dynamically loaded content featuring popovers which need to be bound to the body for correct loading and appearance. I am looking for a solution to hide the popovers when a user clicks outside them or on another popover trigger. After some ...

There was an issue with the rendering: "TypeError: Unable to access the property 'text' because it is undefined"

There is an issue when it comes to rendering the content.link.text property in this code. It shows a Error in render: "TypeError: Cannot read property 'text' of undefined", although there are no errors when passing the title and description. Par ...

Combine several items to form a single entity

When I have two objects returned from the database, my goal is to combine them into one object. Here are the examples: { "id": 4, "first_name": "s", "last_name": "a", ...

My attempts to utilize AJAX to execute a php function have been unsuccessful

Having trouble getting an ajax call to trigger a php function and return successfully. The syntax seems correct, but all I'm getting back is "failed." Any ideas? EDIT I tried changing my AJAX request to send without using data, ruling out that as a ...

Simultaneous Push and Insert operations with Vue.js and PHP

I am looking to add a value into an Array and have it displayed instantly without the need to refresh the entire page. app.todoList.push(this.todo) This line accomplishes that task. Simultaneously, I also want to insert this value into a Database. The i ...

Ways to correctly import various CSS files for individual routes in a Vuejs application

Currently, I am in the process of developing a project using Vue.js and Laravel. This project will have distinct layouts for the admin/user panel and landing page, requiring different CSS files to be loaded for each route. At the moment, I am utilizing va ...

The localhost server in my Next.js project is currently not running despite executing the 'npm run dev' command. When trying to access the site, it displays an error message saying "This site can't be

I attempted to install Next.js on my computer and followed the documentation provided to set up a Next.js project. You can find the documentation here. The steps I took were: Ran 'npx create-next-app@latest' Was prompted for the name of my proj ...

Unexpected quirks in Canvg conversion: Strange behavior observed while utilizing a fill URL

I am attempting to use the canvg javascript library to convert an svg to canvas. Within the original svg, there is a rectangle with a fill attribute that references a svg pattern. However, when I convert the svg to canvas using canvg: canvg(document.getE ...

There was a problem encountered while running a GitHub code that was last updated on January 10, 2023

Recently, I embarked on the journey of creating my own private messenger using Flask. The Github code that caught my attention seemed promising. However, upon executing flask run as per the instructions in the provided "README.md" file on Ubuntu 22.04 comm ...

What steps do I need to follow to execute React/Next code that I have downloaded from GitHub?

I recently obtained a zip file from https://github.com/prgrms-web-devcourse/Team_Price_Offer_FE and extracted its contents. When attempting to launch the program in Visual Studio Code, I inputted the command npm start but encountered an issue. Team_Price_ ...

Design a TypeScript interface inspired by a set static array

I am working with an array of predefined strings and I need to create an interface based on them. To illustrate, here is an example of pseudo-interfaces: const options = ["option1", "option2", "option3"]; interface Selection { choice: keyof options; ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...

utilizing numerous conditional renderings within a mapping function

Hello there, I'm curious if there is a more efficient method to display my todos. Currently, my code looks like this: { todos.map((todo) => ( todo.status === 1 && ( ...

The radio button functionality is not functioning properly as intended

Having trouble with the current code that utilizes HTML and JavaScript. There is an HTML table on the page with a radio button and 4 other fields. The table is generated dynamically when values are set through the controller. It is also possible to add new ...

Utilizing Bootstrap Modal functionality in a Django web application to enhance user experience

I am currently facing a minor issue in my Django application. I am attempting to utilize a modal from Bootstrap 4 along with AJAX to create a new object. Below you can view the code I used. However, when the user clicks the button, instead of seeing the mo ...

What could be causing my React Router component to display incorrect styling?

While working with react-router, I encountered an issue where the text from the routed page started appearing in the navbar. Even though I separated it as its own component and it functions correctly, this specific problem persists. As a newcomer to React, ...