Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function defined within the fetch outside of it, as it seems to be encapsulated within the fetch function.

Despite my efforts to find a solution online and by reaching out for help, I have not been able to resolve this issue. As someone new to JavaScript, I acknowledge that my code may not be well-organized.

Here is a portion of the code causing the problem:

fetch(api_TreeURL)
    .then(function(response) {
        return response.json()
    }).then(function(json) {
        function GetSortOrder(prop) {    
            return function(a, b) {    
                if (a[prop] > b[prop]) {    
                    return 1;    
                } else if (a[prop] < b[prop]) {    
                    return -1;    
                }    
                return 0;    
            }    
        }    

        function DELTA_location(currrentlLocation) {
            var parentlocation = document.getElementById("delta");
            var dirLocation = document.createElement("div")
            var dirLocationText = document.createElementNS("http://www.w3.org/1999/xhtml","a")
            var lastChar = currrentlLocation.substr(-1);
            
            parentlocation.append(dirLocation)
            dirLocation.append(dirLocationText)
            dirLocation.setAttribute("class","delta-location")
        
            if (lastChar != '/') {
                currrentlLocation = currrentlLocation + '/';
            }
        
            dirLocationText.innerHTML = currrentlLocation
        }
    }).catch(function(ex) {
        console.log('parsing failed', ex)
})

Trying to call DELTA_location("") from outside the fetch block results in an error like this:

fetch(api_TreeURL)
    "...the code..."
})

DELTA_location("test")

The error message reads:

Uncaught ReferenceError: DELTA_fetch is not defined
. This error also occurs when attempting to call it from an HTML button.

If you wish to see the entire code, you can visit the GitHub page.

Answer №1

If you're looking to implement a function referencing method, consider the following approach: Once you write the fetch code, define a variable outside with a default function:

let DELTA_location_ref = (a) => console.warn('Function not fetched yet');

Then, within the fetch code, update this variable as follows:

DELTA_location_ref = (currrentlLocation) =>  {
        var parentlocation = document.getElementById("delta");
        var dirLocation = document.createElement("div")
        var dirLocationText = document.createElementNS("http://www.w3.org/1999/xhtml","a")
        var lastChar = currrentlLocation.substr(-1);
        
        parentlocation.append(dirLocation)
        dirLocation.append(dirLocationText)
        dirLocation.setAttribute("class","delta-location")
    
        if (lastChar != '/') {
            currrentlLocation = currrentlLocation + '/';
        }
    
        dirLocationText.innerHTML = currrentlLocation
    }

Utilizing closures (arrow functions) is crucial in ensuring access to the fetch context from external calls.

It's worth noting that your delta location function doesn't utilize the return value of the fetch (json variable), raising questions on its placement within the code structure.

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 is the proper way to define the type for a functional React component by using object destructuring on props?

As I continue to learn TypeScript and work on declaring advanced types, I am faced with converting my CRA project to TypeScript. Within this project, I have a component that closely resembles examples from react-router-dom, but I have not come across any T ...

HTML/PHP/JS - Submit Form and Upload File Simultaneously

I need to create a form with a Photo Upload Input that allows users to upload pictures before submitting the form for faster processing. The form should also support uploading multiple files, display a progress bar, and provide a preview of the uploaded im ...

Using axios to retrieve data and then sending it to a localhost server using express

I'm a beginner in javascript and currently experimenting with fetching data from an API and posting it to my own server (localhost). For fetching the data, I am using axios as shown below: async function getNCAA() { axios .get(`https://api.th ...

Solving the checkbox toggle challenge with recursive functions | Recursive checkbox challenge

I'm currently working on creating a checkbox tree with the following data structure for items const checkboxes = [{ field: 'ARTICLE', id: 41, name: 'Article', parentId: null, checked: false, children: [ ...

tips for passing value to the date field using proctractor

This is the HTML code I am working with: <input id="filter-datepicker" type="daterange" ranges="ranges" class="form-control date-picker" placeholder="Select Date Range" name="sensorDetails.date" ng-model="myDateRange" ranges="ranges" requi ...

What tool can be used for formatting and syntax highlighting when working with ejs (embedded javascript) templates?

When working on my project, I utilize EJS as the express templating engine. While it is user-friendly and efficient, I have encountered difficulties when it comes to editing files - the text highlighting could be better, and I have not been able to find an ...

What is the best way to store textarea information into a session using the jQuery AJAX post method in Codeigniter?

I am having trouble saving the text from a textarea to the Controller session using jQuery AJAX post method in Codeigniter Smarty. I am unable to save the data to the session. Can someone please provide me with guidance and a detailed example of how to ach ...

What could be causing the issue of React not showing the messages of "hello" or "goodbye"?

I have a page with a single button that is supposed to display either "hello world" or "goodbye world" when clicked. However, I am facing issues as the messages are not showing up as expected. Below is a screenshot of what the menu items look like when ca ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

Retrieve dashboard configurations in AngularJS by making an $http request prior to initiating the dashboard controller

I am currently immersing myself in Angular and tackling a complex dashboard framework all built with Angular. Prior to loading the controllers, I need to fetch various dashboard settings from the server using $HTTP. These settings play a crucial role in de ...

The AngularJS Factory $http encounters an error when attempting to read the property 'length' of an undefined value

I am looking to implement a factory in my REST Controller that will return an array of Strings. I want to be able to reuse this function in my services.js file. Here is the HTML for an Autocomplete input field: <input type="text" ng-model="vertrag.ver ...

Using scale transformations to animate SVG group elements

I am currently experimenting with an SVG example where I hover over specific elements to expand or scale them. However, I seem to have made a mistake somewhere or missed something important. Can someone offer me assistance? View the demo on JSFiddle here ...

Tips on assigning a data-id attribute

After a click event, I am attempting to dynamically set the data-id and/or value of a span using my JavaScript file. <span id="test"></span> Here is an example of the JavaScript code: nextLink: function(event) { $('#test').val ...

Map image showing only the tile layer in the top corner

My current project involves utilizing Ionic 5 and Vue.js. One of the screens in my project features a leaflet map that needs to cover most of the screen space. To implement this, I have integrated the Leaflet library for vue into my code. Here is a snippe ...

Having trouble with publishing to npm as public with the --access flag not functioning properly?

When trying to publish a fresh scoped package on NPM using the command npm publish --access public, I encountered the following error: ole@mki:~/cli$ npm publish --access public npm ERR! publish Failed PUT 403 npm ERR! code E403 npm ERR! F ...

What is the best way to upload a file using AJAX request in Sinatra?

I am attempting to upload a file using a jQuery AJAX function with a Ruby-Sinatra function. Here is the code snippet: <form id="ucform" method="post" action="#" enctype="multipart/form-data"> <input type="file" id="cfile" name="cfile" onchange= ...

Syntax Error in Node.js for MongoDB: Unexpected token or invalid symbol

I'm having trouble figuring out what's going on. Node v16.4.2, NPM v7.18.1 const mongoose = require("mongoose"); // const dotenv = require('dotenv') require('dotenv').config({path:'variables.env'}); mongoo ...

An error message indicating that the page is currently being unloaded has appeared

While working on a NodeJS-ReactJS Isomorphic App, I encountered an issue when clicking on a Link. An error message popped up saying: Uncaught (in promise) Error: Request has been terminated Possible causes: the network is offline, Origin is not allowed by ...

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...

Node.js is known for its ability to export both reference and pointer values

Having an issue with exporting my routing table from my express application. In the /bin/www.js file, there is a global variable representing the routing table: var routingTable = []; To create a simple route, new routing objects are pushed using the se ...