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

Livereload.js is failing to load due to an invalid address

Snippet from Gruntfile.js: connect: { options: { port: 4000, hostname: 'localhost', livereload: 4002 }, livereload: { options: { open: true, middleware: function (connect) { return [ connect.st ...

Could the Redux store be used to access the state related to specific review comments?

I have a react class component that includes state variables. class NewComponent extends Component { state = { modalIsOpen: false, aa: true, bb: false, cc: false, dd: false, ee: 1, dd: [], cc: [], ff: [], gg: [], ...

Leveraging Selenium to dismiss a browser pop-up

While scraping data from Investing.com, I encountered a pop-up on the website. Despite searching for a clickable button within the elements, I couldn't locate anything suitable. On the element page, all I could find related to the 'X' to cl ...

Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so muc ...

What is the preferred method for transferring server-side data to JavaScript: Using Scriplets or making an AJAX call?

At the server side, there is a property file that contains a list of words separated by commas. words.for.js=some,comma,separated,words The goal is to convert these words into a JavaScript array. var words = [some,comma,separated,words]; There are two ...

Upgrading from version 3 to version 5 in d3 does not just update the visualization but also introduces a new one

I attempted to upgrade this d3 visualization from version 3 to version 5, but instead of updating within the existing visualization, it continues to add another visualization below. I included: d3.select(".node").selectAll("*").remove(); d3.select(". ...

Headers with a 3 pixel stroke applied

I have a design on my website that includes a 3px stroke around the header text to maintain consistency. I don't want to use images for this due to issues with maintenance and site overhead. While I know about the text-stroke property, browser suppor ...

React-Redux showing no errors despite non-functional Redux store

I'm currently facing an issue with integrating React-Redux into my React Native/Expo project. Despite not receiving any console error messages, the data from the Redux store is not displaying in the user interface. Below are some key files related to ...

Encountering a problem with the scope of child_process in Node

When utilizing the child_process module in Node.js with the fork method, I am able to send data to a specific file and receive a response. However, I am not logging this data to the console after receiving it from the execution process. The code in first. ...

Using React's higher order component (HOC) in TypeScript may trigger warnings when transitioning from non-TypeScript environments

I have a simple HOC component implemented in React with TypeScript. export const withFirebase = <P extends object>( Component: React.ComponentType<P> ) => class WithFirebase extends React.Component<P> { render() { return ...

Validating phone numbers in Saudi Arabia for both mobile and landlines

I've been struggling to validate a Saudi Arabia phone number on my Bootstrap form, but I keep running into an invalid error. Here is the current regex pattern I am using: /^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/ function ch ...

Error: Attempting to use the 'append' method on an object that does not support the FormData interface

$(document).on('submit','#form_pem', function(event){ event.preventDefault(); var kode = $('#kode').val(); var name = $('#name').val; var price = $('#price'). ...

Encountering a situation where an empty object is received while attempting to send a

While using Postman to make a request to the API I created for Social Media Application that involves following and followers functionality, I noticed that I am receiving an empty object: {}. However, upon inspection, everything seems to be correct on my e ...

Is it possible to access the ID element of HTML using a variable in jQuery?

I have fetched some data from a JSON ARRAY. These values include Value1,Value2, and Value3. Additionally, I have an HTML checkbox with an ID matching the values in the array. My goal is to automatically select the checkbox that corresponds to the value re ...

Setting up a plan for executing Javascript server side scripts

Can JavaScript be executed server-side? If I attempt to access a script , can it be scheduled to run every four hours? Would most web hosts allow this, or is it considered poor webmaster practice? The main goal is to activate my website's webcrawler/ ...

Disable Autocomplete Chip functionality when only one can be selected

When multiple is set to true, I prefer the Chip option. Is there a way to enable the Chip functionality even when multiple is set to false? <Autocomplete className={classes.search} options={top100Films} ge ...

When trying to link a Redis microservice with NestJS, the application becomes unresponsive

I am attempting to create a basic hybrid app following the guidance provided by Nest's documentation, but I have run into an issue where the app becomes unresponsive without any errors being thrown. main.ts import { NestFactory } from '@nestjs/c ...

Error message in the browser console: Uncaught TypeError - The function allSections.addEventListener is not recognized

Whenever I inspect my browser console, I keep encountering this error: Uncaught TypeError: allSections.addEventListener is not a function at PageTransitions (app.js:16:17) at app.js:33:1 I find it strange because my VS Code editor does not display any err ...

Refreshing certain sections of a webpage without the need to refresh the entire page

If you want to understand better, it would be helpful if you could check out my website first at: The main part of the website is a stream from Own3D.tv displayed through an iframe (line 342). My objective is to have the ability to click on a specific str ...

AngularJS: Establishing effective communication channels among directives

I am currently developing a custom directive for an audio player that supports mp3 files. The challenge I'm facing is how to handle multiple instances of the player on a single page. My goal is to ensure that when one player is active, starting anothe ...