The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API.

export class ListaGifsComponent {
    gifs : Object[] = [];
    urlBase = "http://api.giphy.com/v1/gifs/search?q=";
    termoPesquisado = "ryan+gosling";
    key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn";
    constructor(http: Http){
        http
        .get(this.urlBase + this.termoPesquisado + 
            "&api_key=" + this.key + "&limit=10")
        .map(res => res.json())
        .subscribe(gifs => 
            this.gifs = gifs['data'],
            erro => console.log(erro)
        );

    }
}

When I use console.log(this.gifs), nothing is logged.

However, if I use console.log(gifs) within the arrow function, it displays the desired object.

How can I resolve this issue?

Answer №1

The situation you are explaining is referred to as a race condition. The arrow function located within the .subscribe() method acts as a callback function, which means it executes after the HTTP get request is completed. However, this function does not block the rest of your code from executing. Consequently, there is a possibility that this.gifs may not have been assigned a value by the time you attempt to console.log it.

To address this issue, consider using reactive data structures such as Promises or RxJS. These will allow you to access the value of this.gifs only once it has been properly set.

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

What could be causing this code to fail in making changes to the HTML document?

I tried incorporating the following code into my website: $('.feed-item').append('<p> This is paragraph element. </p>'); You can view it on this page: Test Unfortunately, the code does not seem to be functioning properly. ...

When you make a POST request to an express API, the properties are not clearly defined

Just getting into Vue.JS and experimenting with creating a basic MEVN to-do list app for practice. I keep encountering an issue when trying to send a POST request to my express server, receiving the error message: TypeError: Cannot read properties of unde ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

Transferring an array from JavaScript to PHP, encountering an issue with determining the length

I'm having an issue passing an array from my .js file to a PHP file. In JavaScript, the array is structured as follows: theBlock[0 - 79] with color, x, and y values. For example, theBlock[10].color or theBlock[79].x The data is sent using the follow ...

Guide on creating and deploying an iOS API file onto a physical device with a Mac computer

I recently switched to using a Mac and have installed Xcode successfully, along with adding the platform for iOS. However, when I use adb devices, my iPhone device is not detected, but my Android device is recognized when connected. Additionally, when ru ...

The JavaScript function Date().timeIntervalSince1970 allows you to retrieve the time

For my React Native app, I currently set the date like this: new Date().getTime() For my Swift App, I use: Date().timeIntervalSince1970 Is there a JavaScript equivalent to Date().timeIntervalSince1970, or vice versa (as the data is stored in Firebase clo ...

The conundrum of jsPDF's image compatibility

I am attempting to generate a PDF document on the client-side using the jsPDF library. The code I have written is as follows: <script type="text/javascript" src="libs/base64.js"></script> <script type="text/javascript" src="libs/sprintf.js" ...

What are the steps to integrate material-ui with styled-components effectively?

import styled from "styled-components"; import Button from "@material-ui/core/Button"; export const StyledButton = styled(Button)` margin: 20px; `; I'm having trouble adjusting the button styling. How can I add a margin to the ...

yii CGridView refresh trigger an influx of Ajax requests

Does anyone know why the yii cgridview refresh button triggers multiple ajax calls? Upon refreshing, I have noticed that it initiates several ajax calls (this time it's 3, but sometimes it's 4 or even 5) GET http://localhost/ijob-css/index.php/ ...

How to retrieve JSON data in Angular.js

I'm having trouble accessing a json file in angular.js with the code below. I keep getting an error message and could really use some help! Here is my module : angular.module("demoApp", ['demoApp.factory','demoApp.controllers']); ...

What is the best way to connect a fresh post to a different URL in ReactJS and Redux?

Currently, I am working with Redux and ReactJS to develop a discussion platform. One of the key features I am trying to implement is where users can input the title and content of their post, which will then be submitted to create a new post. After submit ...

Tips for altering the background of a video on Vonage

Hello everyone, Currently, I am incorporating the Vonage API for video calling into my project. I would like to tweak the video background - does anyone have any ideas on how to accomplish this? I eagerly await your responses! Thank you in advance! ...

Node getting started with YouTube API error

Currently, I'm working through the YouTube documentation to get started with Node.js. https://developers.google.com/youtube/v3/quickstart/nodejs. I've already downloaded the client_secret.json file into my working directory as instructed, but up ...

Transform the selected component in Material-UI from being a function to a class

Hello, I am currently learning about React and I have started using the select button from material-ui. The code I found on the material ui page is for a functional component, but I am more comfortable with class components. Here is the code snippet provid ...

The lifespan of my cookie is limited

I am utilizing the jQuery.min.js from https://github.com/carhartl/jquery-cookie and my cookie code looks like this: $(function() { //hide all divs just for the purpose of this example, //you should have the divs hidden with your css //check ...

Launching a Node.js application on a Kubernetes cluster

Currently, I have a local Angular 6 application that I run using "npm start." My next goal is to deploy this application in Kubernetes. However, I'm unsure about how to dockerize an Angular 6 based application and run it in Kubernetes. Any assistance ...

What is the advantage of not importing related modules?

As a newcomer to React, please excuse any novice questions I may have. I am currently utilizing npx create-react-app to develop a React app, but I'm unsure of the inner workings: Q1-If I were to throw an error in a component like so: import React, { ...

Why won't my AngularJS checkbox stay checked?

In my application, I have the following code: <input type="checkbox" ng-checked="vm.eduToEdit.test" /> {{vm.eduToEdit.test}} <input type="checkbox" ng-model="vm.eduToEdit.test"> The value of vm.eduToEdit.test is displaying t ...

The page switch with a jittery effect

Could really use some assistance with this code that has been giving me trouble for quite a while now. It's a simple HTML, CSS, and JS code involving two pages. [The second page overlaps the first by default, but adjusting the z-index of the first p ...

Guide on extracting unique key values from an array by utilizing a different key

I have an array containing the names of products along with their storage capacities. let products = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storag ...