The Vue app utilizing Flickr API encounters an issue: "Unable to assign value to 'data' property as it is undefined."

Beginning the development of a simple one-page photo stream app using the public Flickr stream, I've encountered an error in my code:

'Cannot set property 'data' of undefined'.

Here is a snippet of my code:

 <b-container>
    <b-row>
      <b-col>
      <p md="4" v-for="photo in Photos">{{photo.id}}</p>
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
    import jsonp from "jsonp";

export default {
    name: 'PhotoFeed',
    data: function() {
        return {
            Photos: [],
            apiURL: "https://api.flickr.com/services/feeds/photos_public.gne?format=json"
        }
    },
    mounted(){
        this.getFlickrFeed();
    },
    methods: {
        getFlickrFeed(){
            let jsonp = require('jsonp');

            jsonp(this.apiURL, {name:'jsonFlickrFeed'}, function(err,data) {
                this.data = data;
                var self = this;
                if (err){
                    console.log(err.message);
                }
                else {
                    this.Photos = self.data;
                }
            });
        }
    }
}
</script>

Answer №1

To prevent the this keyword from being shadowed by the new function, it is important to declare var self = this outside the anonymous function definition.

getFlickrFeed () {
    let jsonp = require('jsonp');
    var self = this;     // Establishing a reference to the Vue component allows access to the Photos property in data

    jsonp(this.apiURL, { name:'jsonFlickrFeed' }, function (err,data) {

        if (err){
            console.log(err.message);
        }
        else {
            // Using self.Photos enables referencing the Vue component
            self.Photos = data;
        }
    });
}

An alternative solution is utilizing an arrow function instead of an anonymous function:

jsonp(this.apiURL, { name:'jsonFlickrFeed' }, (err, data) => {
    if (err) {
        console.log(err.message);
    }
    else {
        this.Photos = data;
    }
})

Answer №2

To utilize an arrow function ()=>, simply incorporate this within the callback context like so:

           jsonp(this.apiURL, {name:'jsonFlickrFeed'}, (err,data)=> {
            this.data = data;
            if (err){
                console.log(err.message);
            }
            else {
                this.Photos = this.data;
            }
        });

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

"Trouble arose when I tried to incorporate additional functions into my JavaScript code; my prompt feature is not

As a beginner in HTML and JS coding, I am working on creating a page that prompts user input for a name and then executes animations using radio buttons. However, after adding functions for radio button changes, my prompt is no longer functioning properly. ...

Adding data to a subdocument array with Mongoose's $push method

Here is the model that I am working with: var Customer = mongoose.model('Customer', { firstname : String, lastname : String, phone : String, street : String, city : String, state : String, zip : String, fixed : Bo ...

Issue: Package 'cairo' not located on EC2 Bitnami MEAN server

Setting up my MEAN application on a Bitnami server has been quite a challenge. During the installation of dependencies, I encountered an error that I just can't seem to resolve. Despite following the instructions provided in the error message, I am st ...

The JQuery command to set the display property to "block" is not functioning as expected

When trying to toggle the visibility of my TextBox based on a selected value in a RadiobuttonList, I initially wrote the following code: $("#<%= rbtnIsPFEnabled.ClientID %>").click(function () { pfno = $("#<%= txtPFNo.ClientID %&g ...

How to enable CORS in Flask while avoiding the "Response to preflight request does not have an HTTP ok status" issue

Seeking assistance with setting up client-side Javascript code to send post requests to my Flask backend. I referenced this helpful answer regarding an issue with flask-cors being blocked by CORS policy, resulting in a preflight request error without passi ...

Removing a value from a JSON object by utilizing the .map function

My JSON object is structured as follows: [{"box":1,"parent":[],"child":[{"boxId":2},{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}] I am attempting to remove the element "child":[{"boxId":2} with boxId=2 from the object. I have tried using a , ...

Updating an object with AngularJS

Let's consider the code snippet below: var absenceType = {name: 'hello'}; this.newAbsenceType = angular.copy(absenceType); After making changes to this.newAbsenceType, you want to apply these changes to the original object. I have explore ...

Converting a Java Object array to a JavaScript Object Array when passing it as a

Is there a way to send a Java array of objects to a JavaScript function? Here is an example object: class SitioMapa{ String title; double lat; double lng; String description; public SitioMapa(String title,double lat,double lng,String ...

Firebase cloud function encountered an issue: Error: EISDIR - attempting to perform an unauthorized operation on a directory

I am currently working on a task that involves downloading an image from a URL and then uploading it to my Firebase cloud storage. Below is the code I have implemented for this process. import * as functions from 'firebase-functions'; import * a ...

What causes the server to give an incorrect response despite receiving a correctly read request?

After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code: const express = require('express'); const app = express(); ...

Coarse patterns blending in a minimalist box setting

I am new to the world of three.js and recently attempted to create a simple textured cube box in an isometric view. However, when I added edge lines to my cube, I noticed that some edges appeared grainy. Despite experimenting with adjustments to the camer ...

Rearrange the sequence of numbers using JQuery when an HTML element is deleted

I'm currently working on a simple functionality where I have 5 rows, each with its own number. So initially, the rows are numbered from 5 to 1. If I remove a value like 3, the sequence should adjust to 4, 2, 1, indicating that I now have only 4 rows ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

The style properties of Material UI ButtonGroup are not being properly applied

https://i.sstatic.net/apxUH.gif Within a Grid container, I have a Product image with associated buttons. The visibility of these buttons is determined by specific state variables. If the product quantity is 0, an "ADD TO CART" button is displayed; otherwi ...

Accessing the value returned by an asynchronous function in Node.js with Electron

As I embark on a new project, my goal is to take user input, process it through a function, and then return the updated value back to the user. Despite being a novice with async functions, I've done extensive research but still can't pinpoint if ...

Conceal the loading image once the AJAX function has been successfully

I've been trying to figure out a way to load heavy images after an ajax call using animated GIF as a pre-loader, but haven't found a satisfactory solution yet. Here's the code snippet I'm currently using: function loadProducts(url) { ...

Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts. Currently, I am facing an issue where I need to load a file, but due to its ...

Creating an HTML table from an array in an email using PHP

How can I use data collected by Javascript to generate an email in PHP? The array structure in JavaScript is like this: Menu[ item(name,price,multiplier[],ingred), item(name,price,multiplier[],ingred) ] The array Menu[] is dynamically cr ...

The credentials in AWS S3Client are failing to load correctly

I encountered an issue with the S3 Client from aws sdk v3: When using the S3Client as outlined in the documentation and providing credentials via environment variables, I received an error message stating The AWS Access Key Id you provided does not exist ...

Having trouble launching Cypress on my Mac - stating that it cannot find Cypress

Despite searching through multiple answers on S.O, none of them have solved my issue. To better explain my question, I've created a video. You can view it here Everything was working perfectly just yesterday, so what could have possibly gone wrong? ...