1

Just need to access baseUrl in the post method on the code below. What is the correct method of doing so? And if you can explain to me why this does not work I would be thankful.

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); // shows undefined so I can't access this.baseUrl inside this 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;
      });
  }
};

As requested:

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);
  });

The code above works if I replace this.baseUrl with "http://my_api_address" so I don't think there is any other issue.

  • Don't use an arrow function for the post method. Just use `function(){}`. Arrow functions don't bind their own context but use the context from the position of definition. – Teemoh Nov 18 '18 at 19:27
  • Change `post: (path, payload) => {` to `post(path, payload) {` in order for it to be possible to access `this` – 4castle Nov 18 '18 at 19:29

1 Answers1

2

It's because for post: you used an arrow function, which doesn't bind its own this, but rather uses the closest lexically defined one (if any).

Use function() {...} syntax instead.

Note that you didn't show the call to API.post(), so there could be other issues too

ziggy wiggy
  • 1,039
  • 6
  • 6