Is the JSON returned by the API server not being properly processed by the RequireJS module, resulting

After extensive research on promises and module creation, I am still unable to understand why my current setup is not functioning properly.

My goal is to write a script that takes a username and then fetches user data from a 3rd party API using a separate module. While everything works fine when the code is in one script, I seem to be making a mistake when trying to extract and separate the API request into its own module. These components are built using durandal as a framework.

Here is the script:

define(function(require) {
var http = require('plugins/http'),
    ko = require('knockout'),
    apiPullMod = require('apiPullMod');

return {
    name: ko.observable('RyeBrush'),
    nameInfo: ko.observableArray([]),
    getSummoner: function() {
        var that = this;
        if (!that.nameInfo()) {
            return;
        } else {
            that.nameInfo.push(apiPullMod.apiCaller('v1.4/summoner/by-name', that.name(), 'na'))
        };
        console.log(that.nameInfo);
    }
};
});

The separate module:

define(['plugins/http'], function(http) {
    return {
        apiCaller: function(apiType, apiUserId, region) {
            http.get('https://' + region + '.api.pvp.net/api/lol/' + region + '/' + apiType + '/' + apiUserId + '?api_key=282d6dcb-a047-4262-88d0-c53b0e28e6ef', 'jsoncallback').then(function(response) {
                console.log(response);
                return response;
            })
        }
    }
});

Although the API request seems successful and returns the expected JSON object in the console, when pushing it to the nameInfo array, the result is c(). Upon inspection with Firebug, the file path for the knockout library is revealed.

When attempting an alternative solution:

 apiPullMod.apiCaller('v1.4/summoner/by-name', that.name(), 'na').then(function(response){
                that.nameInfo.push(response);
                console.log(response);
            })

The module fails to load, presumably because it lacks a then property within itself. However, based on the documentation for durandal and requirejs, such a property should not be necessary.

To simplify my question: How can I structure both the module and the calling script to successfully pass a JSON object between them?

NOTE: My personal API key has been included in this post, but I can reset it anytime. There are no concerns about API traffic at this early stage of app development.

Answer №1

To potentially resolve the issue, you can modify the apiCaller to return a promise as shown below:

define(['plugins/http'], function(http) {
    return {
        apiCaller: function(apiType, apiUserId, region) {
            return http.get('https://' + region + '.api.pvp.net/api/lol/' + region + '/' + apiType + '/' + apiUserId + '?api_key=282d6dcb-a047-4262-88d0-c53b0e28e6ef', 'jsoncallback');
        }
    };
});

apiPullMod.apiCaller('v1.4/summoner/by-name', that.name(), 'na').then(function(response){
    that.nameInfo.push(response);
    console.log(response);
});

Answer №2

It appears that the http plugin is utilizing knockout's map plugin to convert your response into observables automatically. I suggest considering using jquery's http plugin or a different alternative.

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

Generating JSON output with PHP

Below is the current progress : if (is_request_var('requestor') == 'PPA'){ $dataJson[][] = array("status" => "success","value" => $fetchValue ,"postcode" => $fetchPostCode,"params"=>""); $notice = $dataJson; } I a ...

Having trouble retrieving text from an HTML form in Node.js using express, as the req.body object is coming up

Having trouble extracting text from an HTML form to build a basic text to speech functionality. Despite using an express server, the req.body is consistently empty when attempting to fetch the text. I've experimented with body-parser and adjusted the ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

Top recommendation for creating a customizable grid in Angular

We are currently in the process of transitioning our application from GWT to angular. Within our application, we have implemented an editable grid feature. One method for making the grid editable is to use a separate editor for each cell. However, this ap ...

How to retrieve the $0 element using Python Selenium

There is an unnamed element I can only access with a dollar sign: console.log($0); "100" In Python Selenium, how can I retrieve this element? I attempted the following: my_value=driver.find_element(By.NAME,"$0") However, it resulted i ...

Transform Java String to HashMap Instance

After successfully creating an application to convert a HashMap object to String, I encountered an issue while trying to convert the HashMap string back to a HashMap object. When I attempted this conversion using the provided code snippet, it resulted in a ...

Tips for navigating to the top of the browser window from the middle or bottom using JavaScript in Protractor

I am in need of clicking the element positioned at the bottom of the page first and then I must click on an element located at the top of the page. In other words, scroll up where it is not visible to the browser. To scroll down, I have used: browse ...

Transfer numerical values from PHP to JavaScript using individual files

What is the best way to pass variables from PHP to JavaScript when they are in separate files? Is it possible to achieve this without using AJAX, or is AJAX necessary for this task? If AJAX is required, how can I implement it? test.php <?php $a = 5; $ ...

Managing the rendering of charts in Angular with Directives

I'm in the process of creating an admin page with multiple elements, each revealing more information when clicked - specifically, a high chart graph. However, I've encountered a challenge with the rendering of these charts using a directive. Curr ...

Tips for creating mocks/stubs for vue-i18n?

I have recently made the switch from Jest to Vitest as my unit testing library for my Vue 3 application. Currently, I am facing an issue while trying to write a unit test for a component that utilizes the vue-i18n library for text translation. When attemp ...

Guide on using POST method in jQuery version 1.11.4 for tab functionality

I'm currently in the process of upgrading from jquery ui version 1.9.2 to jquery ui version 1.11.4 and I've encountered a situation where ajaxOptions has been removed from the tabs control. Originally, I was using the following code: $("#tabs"). ...

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

transferring information from child to parent with the help of Vue.js and Laravel

As a newcomer to vue.js, I have a child component called 'test' and a parent component called 'showdata'. My issue arises when I try to emit data from the child to the parent - while the emission is successful, displaying the data in th ...

ReactJS does not recognize the library mentioned

click here to access the pondjs folder inside node-modulesAfter installing pondjs(https://www.npmjs.com/package/pondjs) using npm install pondjs --save in my react application and confirming its presence in package.json, I encountered an issue in App.js. W ...

Creating responsive images in a navbar with HTML and CSS

I need help with this code snippet: <div> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <div class="d-flex flex-row justify-content-center align-items-center"> <a cla ...

What steps should I take to handle and utilize a JSON request that is expected to be improperly structured?

My current project involves setting up a system where I receive a POST request that then triggers another POST request. The issue is that the incoming request has a Content-Type of application/json, but the body data appears to be incorrectly formatted JSO ...

Combining multiple meteor servers into a single database collection (local)

I'm currently working on a Meteor project that involves making multiple external API calls at different intervals and storing the retrieved data in MongoDB. My goal is to separate these API calls into individual "micro-services", each running on its ...

Encountering an error while trying to update a field using the $inc operator in

Currently, I am working on updating a field in my database to increment it each time like a counter. This will allow me to consistently receive the latest values. To achieve this, I have defined the following schema: var CounterSchema = new Schema({ _id: ...