Determining the HTTP method dynamically with Vue Resource

I am trying to dynamically determine the appropriate HTTP method and make a single API call. However, I keep running into an exception when I attempt to call the method.

Instead of assuming it's a bug with vue-resource, I believe I may be making a mistake in my code. Does anyone have any advice on how to resolve this issue? Thanks in advance.

Here is an example of what I'm attempting to do:

let method = this.$http.post

if (this.model.id) {
    method = this.$http.put
}

method(
    this.url,
    this.model,
    options
).then(response => {
    this.$router.push(this.redirect_to)
}).catch(response => {
    console.log(`Error: ${response.statusText}`)
})

When I try to execute the above piece of code, I encounter a javascript TypeError which says "this is not a function".


The following code below does work, but it feels a bit cumbersome to handle both situations separately:

if (this.model.id) {
    this.$http.put(
        this.url,
        this.model,
        options
    ).then(response => {
        this.$router.push(this.redirect_to)
    }).catch(response => {
        console.log(`Error: ${response.statusText}`)
    })

} else {
    this.$http.post(
        this.url,
        this.model,
        options
    ).then(response => {
        this.$router.push(this.redirect_to)
    }).catch(response => {
        console.log(`Error: ${response.statusText}`)
    })
}

Answer №1

Ensure that the function is bound to the present context.

const action = this.model.id ? this.$http.put.bind(this) : this.$http.post.bind(this)

Alternatively, you can utilize the indexer method.

const action = this.model.id ? 'put' : 'post'
this.$http[action](...).then(...)

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 best way to access and utilize the data stored in my database using mySQL, PHP, and JavaScript?

My Objective : When a user selects a location from the dropdown list, I want the function "newMark()" to place a marker on Google Maps; Current Achievements : The map is displayed along with the select field containing all locations saved in my database. ...

Display <tr> tag when button is clicked without refreshing the page

I have a specific requirement to hide a certain tag initially. If the user clicks the forward button without selecting any radio buttons or checkboxes, the tag should be displayed and the page should not refresh. However, there seems to be an issue with ...

Having trouble with the auto-complete feature in the search box when using Jquery

I'm currently working on implementing TypeAhead functionality for a search textbox. Within the form, I have 2 radio buttons and if one of them is selected, I need the type-ahead feature to populate the list of masters in the search box. //html < ...

Methods to Exclude api_key from URL in AngularJS

To make a GET request to a REST API, I require an apikey. The request will be formed like this - $http.get() The response from the API will be in JSON format. However, for security reasons, I don't want the api key to be visible in the URL. Is ther ...

Increment field(s) conditionally while also performing an upsert operation in MongoDB

I need to perform an insert/update operation (upsert) on a document. In the snippet below, there is a syntactical error, but this is what I am attempting to achieve: $inc: { {type=="profileCompletion"?"profileCompletion":"matchNotification"}: 1}, If the ...

React frontend encountered a connectivity issue while trying to establish a network connection

Our app utilizes next.js connected to express, which is further linked to AWS MySql for database management. While attempting to load some products stored in the database, an error message pops up: TypeError: NetworkError when trying to fetch resource. ...

Tips for executing an artillery script with customizable parameters

execute my-script.yaml with artillery To access the target, a token is required for authentication. How can I execute the script above using a token? For example: execute my-script.yaml using token 983r2fh29hf2893yr72 ...

What is the best way to update a data value in one Vue Js component and have it reflected in another component?

I'm a newcomer to Vue Js and encountering an issue with changing data values from another component. Let's start with Component A: <template> <div id="app"> <p v-on:click="test ()">Something</p> </div> ...

AJAX loading footer content before images are fully loaded

I am a beginner when it comes to ajax and I'm facing an issue where the footer loads before the images, causing the images to overlap the footer. The problem is illustrated in the image below. <!doctype html> <html lang="en"> <head ...

Getting started with WebTorrent: A beginner's guide

I have been brainstorming some ideas for using WebTorrent. While I am comfortable with JavaScript and jQuery, I have never ventured into Node.js or Browserify territory. Can someone guide me through how to implement the following straightforward code? var ...

Leveraging props to set the initial value of component data in Vue 3 Composition API

Currently, I am in the process of developing a search page in Vue 3 using the composition API. One of my components is responsible for displaying a snippet of data that includes specific keywords provided by the parent component. To achieve this, I need to ...

How to extract part of a string delimited by certain characters within GET parameters?

I have a requirement to modify an iframe src attribute generated dynamically by a BrightCove video player. Specifically, I need to eliminate certain GET parameters such as width and height, so that the width and height of the parent element take precedence ...

Exploring Techniques for Adjusting Website to User's Screen Resolution

My website is currently designed for a screen resolution of 1024x768. However, I am aware that when viewed on computers with smaller or larger screen resolutions, the layout starts to distort. Is there a way to make the website adaptable to any user&apos ...

What causes the error "Why am I receiving a "Cannot read property 'length' of undefined" when looping through a pug template?

Currently, I am in the process of developing a project using Node and Express. My objective is to have the home page display signup and login links in the nav bar when the user is not logged in. Initially, everything seemed to be working fine, and I was ab ...

Obtaining an identification using JQuery for content that is constantly changing

I am currently developing dynamic content tabs using PHP, with one of the objects being a datatable within the tab. In order to define the ID via PHP, I use the following code: PHP: echo '<table class="table table-striped table-bordered table-hov ...

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

Issue with .submit() not submitting form after setTimeout timer runs out

How can I add a delay after a user clicks submit on a form before it actually submits? I have an image that appears when the click event is triggered, but the form never actually submits... This is the HTML form in question: <form class='loginFor ...

Does the current protected route that I am on restrict the user from navigating back to the Home component?

I'm having trouble figuring out how to redirect the user to the Home component when they logout. The API is functioning correctly based on my tests. However, I am unsure of how to implement the logout method in the current context to successfully log ...

Is there a barrier I've reached with the amount of hashtags I'm using?

My goal is to limit the use of javascript and rely more on CSS to achieve desired effects on my website. One feature I have developed is a modal that opens using hashtags and targets, similar to this example: http://codepen.io/maccadb7/pen/nbHEg. While th ...

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...