What is preventing me from being able to access a property within my function?

In the post method below, I am trying to access baseUrl. However, it is showing undefined. Can you help me understand why and provide a solution?

const API = {
  baseUrl: "http://my_api_address",

  post: (path, payload) => {
    let headers = {
      Accept: "application/json",
      "Content-Type": "application/json"
    };

    let token = localStorage.getItem("accessToken");
    if (token) {
      headers["Authorization"] = "Bearer " + token;
    }

    alert(this); // This shows undefined, preventing access to this.baseUrl within the function

    return fetch(this.baseUrl + path, {
      method: "POST",
      headers,
      body: JSON.stringify(payload)
   })
      .then(res => {
        return res.json().then(json => ({ json, res }));
      })
      .then(({ json, res }) => {
        if (!res.ok) {
          return Promise.reject(json);
        }

        return json;
      });
  }
};

Here's the code where I'm calling the post method:

API.post("/account/resetpassword", data)
  .then(function(json) {
    UI.toggleModal("#modalId");
    UI.loader("hide");
    UI.alert(json.success, json.message);
  })
  .catch(function(json) {
    console.log(json);
  });

I found that replacing this.baseUrl with "http://my_api_address" makes the code work fine. So, it seems the issue lies in accessing this.baseUrl.

Answer №1

The reason is that when you used an arrow function for post:, it doesn't bind its own this, but rather uses the closest lexically defined one (if any).

Try using the function() {...} syntax instead.

It's worth noting that since you didn't show the call to API.post(), there could be other issues present as well.

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

Web browser local storage

Looking to store the value of an input text box in local storage when a button is submitted <html> <body action="Servlet.do" > <input type="text" name="a"/> <button type="submit"></button> </body> </html> Any sug ...

Javascript enables dynamic field addition to tables

I have JSON data that needs to be displayed in an HTML table. To input the values, I have individual fields for firstname, lastname, email, and phone number, along with an "Add Row" button. When I click the "Add Row" button, I want the entered values to b ...

Horizontal scroll box content is being truncated

I've been trying to insert code into my HTML using JavaScript, but I'm facing a problem where the code is getting truncated or cut off. Here's the snippet of code causing the issue: function feedbackDiv(feedback_id, feedback_title, feedb ...

Turn off and then turn on user input without exiting the textarea

I've been working on a small project that requires me to enable and disable text input in a textarea using key commands, similar to Vi/Vim's insertion and command modes. However, I'm struggling to find an elegant solution. Disabling the tex ...

Is it possible to extract tooltip text from a website using Python and Selenium, specifically when the text is generated by JavaScript?

Can anyone help me retrieve the tooltip text that appears when I hover over the time indicating how long ago a game was played? You can find my summoner profile here. I have noticed that the tooltip text is not visible in the HTML code and suspect it may ...

Utilizing ReactStrap: a guide to retrieving the id of the chosen dropDownItem

In my code, I have a dropdownList component with various DropdownItems: <Dropdown isOpen={this.state.dropdownOpen[3]} toggle={() => { this.toggle(3); }} > <DropdownToggle className="my-dropdown" car ...

How to prevent the collapse action when clicking a button inside a div in Bootstrap 5 using data-bs-toggle

My div contains a data-bs-toggle attribute along with buttons. https://i.sstatic.net/RzagX.png When clicking on the panel, it collapses. However, I do not want this collapse event to trigger when clicking the buttons. Is there a way to control this behav ...

Utilize JavaScript to compute and implement a deeper shade of background color

To dynamically apply darker shades of background using JavaScript, I have devised the following code. .event-list .bg{ background:#eee; padding:5px; } .grid .event-list:first-child .bg{ background: #2aac97 } .grid .event-list:nth-child(2) .bg{ backgrou ...

Reset the select boxes when a button is clicked

I'm currently utilizing Devextreme within my Angular application, and I have three dx-selectbox elements in the component. I am attempting to clear all three dropdown selections when clicking a "clear" button. Unfortunately, I am unable to find a way ...

Is there a way to access multiple values from my function array in Javascript instead of just the first one?

function findDistinctElements(inputArray) { let distinctItems = []; for (let i = 0; i < inputArray.length; i++) { const currentItem = inputArray[i]; if (!distinctItems.includes(currentItem)) { console.log(`Argument ${i+1}: $ ...

What is the reason for not using constants for events in the Node.js programming language?

Although I am new to node.js, my programming background is extensive. I have noticed that in tutorials and production code, developers tend to use hard-coded strings rather than constants to identify events. To illustrate this point, I randomly selected a ...

Passing the IDs of other elements as arguments when invoking a JavaScript function

Greetings, as I work on a jQuery mobile app, a particular scenario has arisen that requires attention. <script> function showPanel(info) { alert(info.id); } </script> <div data-role=" ...

What is the best way to fully eliminate the Pixi renderer, stage, and all associated assets

I am currently faced with a challenge of mounting and unmounting a Pixi stage using React without relying on react-pixi. Upon re-mounting the component, I encounter the following error: Uncaught Error: Resource with name "cupCake.png" already exists i.ad ...

Loading JavaScript in the background using Java and HtmlUnit

I am currently facing a challenge while navigating a website using HtmlUnit. This particular website adjusts certain buttons and displays or hides certain elements based on JavaScript events. For instance, there is a text input box along with a button th ...

What is the best way to evaluate two objects with varying data types?

Is it possible to compare two objects with different data types? var a = { sort: 7, start: "0"} var b = { sort: "7", start: "0"} I thought they should be equal, but when I try using JSON.stringify(a) === JSON.stringify(b), it returns false. ...

Troubleshoot the pattern of Pascal's Triangle

Can someone help me understand what's wrong with my implementation of Pascal's Triangle in JavaScript? I came across a similar thread discussing recursion, but I'm having trouble figuring out the errors in my code. I would appreciate fresh e ...

Two-way data bindings trigger the digest() function to iterate 10 times

I'm facing issues with angular binding and my experience level in this area is limited. I will be posting all related questions here. I have a piece of angularjs code that is triggering 10 digest() cycle reached errors. After researching similar posts ...

Creating a customized store locator using JSON data in WordPress for Google Maps API

I'm currently seeking a customized solution to implement a store locator using the Google Maps API within WordPress. Although there are numerous WordPress plugins available, I prefer a more tailored approach. Here are the specific requirements: ...

Creating element modules in EJS

After building experience with React, I am now faced with the task of using ejs in my current project. Specifically, I need to return multiple radio elements. My attempt at achieving this was through the following code: <% const renderRadios = (value, ...

What is the best way to showcase arrays in a JSON document?

I'm working on a basic AJAX code to show a JSON file stored locally using this HTML, but I keep getting an 'undefined' error. I'm opting for JavaScript instead of JQuery since I haven't delved into it yet; hoping my code is syntact ...