Acquire information using Vue through HTTP requests based on Router parameters

I have been searching for a solution to this issue and even referred to the example provided on the Vue Router documentation, but I am still encountering difficulties. My goal is to make an HTTP call when a component loads initially, then monitor the router parameters to update the 'get' call using vue-resource.

Below is my Vue component JS code...

export default {
  name: 'city',
  components: {
    Entry
  },
  data () {
    return {
      city: null
    }
  },
  mounted() {
    this.fetchData();
  },
  watch: {
    '$route': 'fetchData'
  },
  methods: {
    fetchData() {
      const cityName = this.$route.params.name;
      this.$http.get('http://localhost:3000/cities?short=' + cityName).then(function(response){
        this.city = response.data;
      }, function(error){
        alert(error.statusText);
      });
      console.log(cityName)
    }
  }
}

I checked the 'cityName' in my fetchData method and it consistently shows the correct name. However, when I include that 'cityName' in the http get call, it does not retrieve the expected data. On the initial load, this.city remains null, and every time I change the route, the data corresponds to the previous city selected rather than the newly updated city in the route. I attempted using Vue's created property instead of mounted, but encountered the same result. Any suggestions?

Answer №1

Consider updating your fetchData function with the code snippet below:

fetchData() {
  const city = this.$route.params.name;
  this.$http.get('http://localhost:3000/cities?short=' + city).then((response) => {
    this.cityInfo = response.data;
  }, (error) => {
    alert(error.statusText);
  });
  console.log(city)
}

Using the => arrow function helps maintain the correct context of this within the component.

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

Leveraging the power of JavaScript's .map(...) method in a

Within my React code, I have a structure similar to the following: {elements.map((element) => { return ( <div> {renderDate(element.date)} </div> ) }})} This structure calls the renderDate function defined as: co ...

Error: The property 'getClientRects' cannot be read because it is null

I'm brand new to learning about React and I've been attempting to incorporate the example found at: Unfortunately, I've hit a roadblock and can't seem to resolve this pesky error message: TypeError: Cannot read property 'getClient ...

Difficulty displaying a progress bar over an overlay

Issue with Progress Bar Visibility in AJAX Call: I have a requirement to display a progress bar in an overlay after the save button is clicked. However, the progress bar is only visible after we receive the response from the AJAX call and display an aler ...

Retrieve the currently displayed page on a bootstrap table

I'm currently utilizing the bootstrap table to showcase my data. One of the features I have added is a column with an edit button for each row. Upon clicking on the edit button, I open a bootstrap modal that displays the data from the corresponding ro ...

Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs? The default error message structure in NestJS looks like this: { "statusCode": 400, "error": "Bad Request", "message": [ { "target": {} ...

Ways to adjust .keyup based on the presence of a variable

I am currently in the process of constructing a search form that utilizes an ajax function within .keyup, which may have various arguments. I aim to determine if a specific argument should be included based on the presence of another value. Here is my curr ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

What steps should I follow to obtain code coverage data in my Aurelia application with the help of karma?

After creating my Aurelia app using the Aurelia CLI (au new), I wanted to set up code coverage, preferably with karma-coverage, but was open to other options as well. First, I ran npm install karma-coverage --save-dev and then copied the test.js task over ...

Guide on how to activate a hyperlink with a specified target using JavaScript

I have a URL structured like this: <a id="preview" ng-href="/preview/{{accountId}}/app/{{app.id}}" target="preview" class="btn btn-default" style="margin-left: 20px;" ng-hide="isJobMode">Preview</a> This is part of an Angular app, and I am tr ...

HTML - Retain placeholder text while user inputs

My input is structured like this: <input value="My text" placeholder="Placeholder"> Typing in the input causes the placeholder text to disappear, which is expected. However, I am looking to keep the placeholder text visible as a background behind ...

Instructions for incorporating highcharts sub modules into a React application

I have been utilizing the react-jsx-highcharts library to seamlessly integrate Highcharts into my React application. Everything is functioning perfectly. However, I am now interested in incorporating the boost module. I attempted to add it by simply using ...

Execute a post request upon clicking with NEXT JS, while also firing off a get request

I'm facing an issue where I need to post and get my data when clicking on the same button (similar to writing and displaying comments). However, whenever I click the button, everything seems to be working fine but a request with a 304 status code star ...

How can elements be connected in Vue using a delimiter?

When it comes to Python, there is a straightforward method to link elements together with a separator solely placed between the "inner" components: >>> print(" → ".join(['hello', 'world', 'bonjour'])) hello → wor ...

JavaScript - Combining nested arrays of JSON data into a single object

I'm looking to convert a nested JSON structure into a single object with dynamic keys. I attempted the code below, which only works for one level. I need help writing a recursive function to handle n levels of nesting. Any advice would be appreciated. ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

Hmm, seems like there's an issue with the touchable child - it must either be native or forward setNativeProps to

Currently enrolled in a ReactNative course on Coursera, I am facing an error in a 4-year-old course: "Touchable child must either be native or forward setNativeProps to a native component." I am unsure about this error and would greatly appreciate any hel ...

What is the best way to transition an absolute positioned element from right to center?

When hovering over an overlay element, I want the <h3> tag to appear with a transition effect from right to center, similar to the example shown here. Could someone please assist me in achieving this? Thank you in advance. HTML <div class="row m ...

A concise way to write an else if statement in Javascript and jQuery

Is there a way to make this code more concise? It works perfectly fine, but it's too lengthy. Basically, the code involves two dropdown lists where the user selects options, and based on their selection, values appear in two textboxes. The catch is th ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Stopping a function that is currently running on a website using Javascript

I have a script on my website that triggers a rain feature when a user clicks on a button. However, I am struggling to figure out how to allow the user to deactivate this feature. I've tried various methods such as using break, return, and timeouts, b ...