2

I have a Vue application written with Typescript and I'm using Fetch to retrieve data from an api. In one of my components I have the following interface defined:

interface SearchResult {
    device_id: string;
    location: string;
    sub_location: string;
    status: string;
}

In my Fetch method I cast the response.json() promise to an array of the SearchResult interface like so:

fetch(url).then(response => response.json() as Promise<SearchResult[]>)
          .then(data => { 
              this.results = data; 
          })

The issue I have is, if 'status' is not included in the response.json(), no reactive getter is created for this.results.status, meaning I can't mutate the data and have it react on the page.

I tried manually setting the value of 'status' after I the line this.results = data, and when I inspect the object using VueTools I can see it has the status property with the value I assigned it. But the reactive getter and setter is still missing.

I also tried changing the interface to a class with a constructor that set a default value for 'status', but this also failed to create the reactive getter and setter for the property.

How can I create the reactive getters and setters without explicitly adding 'status' (or any other arbitrary properties) to the api response?

1 Answer 1

3

Vue cannot detect properties added to an object that has already been added to data unless you add the property via $set.

Change your fetch response to:

fetch(url)
  .then(response => response.json() as Promise<SearchResult[]>)
  .then(data => { 
    this.results = data; 
    for (let result of this.results)
      this.$set(result, 'status', "some value");
  })

Though you should also be able to get away with:

fetch(url)
  .then(response => response.json() as Promise<SearchResult[]>)
  .then(data => { 
    this.results = data.map(d => d.status = "some value"); 
  })
Sign up to request clarification or add additional context in comments.

2 Comments

The solution I ended up using was the second suggestion. Because data is an array, it was easier to set the property while iterating over it then setting it to this.results. The key was to set the properties on the data object before assigning it to this.results.
@hackintosh Doh, sorry I didn't notice it was an array. Fairly obvious. I updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.