The fetch hook that relies on router parameters fails to function properly when the page is refreshed

When fetching property data via params, the ID's of agents are included in the response. However, I am encountering an issue where manually refreshing the page does not fetch the agent data, but navigating to the page through the app does.

What could be causing this discrepancy? Do I need to adjust how I structure my data fetching process?

async fetchData() {
  try {
    const property = await this.$axios.$get(
      `/api/get-specific-property/${this.$route.params.id}`
    )

    if (property.success) {
      this.property = property.data

      const agentIDs = property.data.agents
      this.fetchAgents(agentIDs)
    }
  } catch (err) {
    console.log(err)
  }
},
methods: {
  async fetchAgents(agentIDs) {
    try {
      const agents = await this.$axios.$post('/api/get-specific-agents', agentIDs)

      if(agents.success) {
        this.agents = agents.data
      }
    } catch(err) {
      console.log(err)
    }
  }
}

Answer №1

It would be wise to pause and wait for your function using the following code snippet

await this.retrieveAgents(agentIDs)

The remaining part seems to be in order!

Answer №2

When utilizing SSR, the fetch() function is automatically executed on the server side.

  • If you set fetchOnServer: false, it will only occur on the client side.

@PhilippeUn suggests using the async/await syntax over try/catch for cleaner code. Additionally, resolving APIs calls in the fetch hook can be simplified by using this.$fetch() to re-run the hook.

  • This approach also enables the usage of $fetchState.error/pending state tracking.

  • A helpful tip is to replace console.log with console.error when logging errors as it provides a trace of the error.

One concern raised is the use of the $POST method instead of GET method for data retrieval. Reference this answer on Stack Overflow: Use GET for requesting data

While POST allows for including a body in the request, it poses significant risks for the backend system.

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

Tips for concealing uib-popover when clicking outside of the popover in Angular JS

<button class="btn btn-default blue btn-lg h-ask btn-block" popover-placement="bottom" uib-popover-template="popover_home.templateUrl">ASK</button> In the code snippet above, there is an angular js popover implementation within an html templat ...

Ways to change an array of objects with similar named values

Here is an array of nested objects: var existingArray = [{ "content": { "host": { "name": "Mia" } }, }, { "content": { "host": { ...

The search function in Select2 is not displaying the desired result

I'm encountering an issue with the search functionality when it uses Ajax to load data from a JSON file. For example, if I search for Yemen, the record for Yemen does not get selected or highlighted properly. Here is the complete source code - could ...

What steps can be taken to ensure that the popover div remains visible when clicking inside it in a "dismissible popover" using Twitter Bootstrap with the data-trigger attribute set to "

I am struggling with a dismissible popover that contains a text box. When I click inside the text box to type, it disappears due to the "data-trigger="focus". Is there a way for the div not to disappear when clicked inside intelligently? Here is the releva ...

Erasing a Cookie

I'm currently developing a feature on my website that involves adding [ITEM] and using cookies. The Add [ITEM] functionality is already working, but now I need to implement a Remove [ITEM] feature. Below is the code snippet I have so far: $(window).l ...

What is the method for setting a variable to an object property's value?

I am currently working on a React app and I have an object structured like this: state = { property1: 'value', property2: 'value', property3: 'value', property4: 'value', } I am trying to write a fu ...

How can a particular route parameter in Vue3 with Typescript be used to retrieve an array of strings?

Encountered a build error: src/views/IndividualProgramView.vue:18:63 - error TS2345: Argument of type 'string | string[]' is not assignable to parameter of type 'string'. Type 'string[]' is not assignable to type 'strin ...

What is the best way to eliminate a specific value within a flatmap?

This is the flatMap: const choices = names.flatMap( (item) => item.name + " - " + item.size + "- " + item.category ); console.log(choices): https://i.stack.imgur.com/MO4b1.png If the item.category is equal to S-XL, how can ...

What is the best way to detach a listener connected to an unidentified function?

Within my component, I have a listener linked to an unidentified function. Is there a way to detach that listener in the future, considering there is no specific function name associated with it? mounted() { EventBus.$on('setStickyHeaderCaption&ap ...

Is it possible to Dispatch a Toggle action in Redux without storing it in the State?

Current Implementation At present, I have a list of items. When the user clicks on button X, the state of shouldShowItem is toggled. This state is managed in Redux and passed down to each individual Item component as a prop, where it can be either true or ...

The express gateway is unable to transfer multipart/formdata

I've implemented express gateway as my main service gateway. One of the services I have needs to update an image, and when I try to handle files independently using multer it works fine. However, once this service is routed through express gateway, th ...

Applying CSS to select a different element style within a webpage

I was thinking about the possibility of linking one style to another using events like :focus or :hover in CSS alone, without the need for JavaScript. For instance, can the class "hitArea" change the background attribute of "changeArea" when it is in foc ...

How To Display Information From a Nested Array Using Mongoose Querying?

Struggling to write a title, but my issue involves a nested array data structure in MongoDB. Here is an example of how it is set up: [ { employee: one, data: [ { year: 2020 }, { year: 2022 ...

What could be the reason for jquery not functioning properly on my website?

Hey there! I'm running into an issue where my jQuery code isn't running. I've tried triggering it on button click or page load, but no luck so far. Any tips would be greatly appreciated. Thanks! <head> <script src ...

Step-by-step guide on implementing a real-time data array counter in React js

I am attempting to create a function that continuously generates new data arrays with an increasing counter. Each second, a new array should be added with the next number in sequence. data={[ { x: 1, y: 1 }, { x: 2, y: 2 }, ...

combining elements in JavaScript

I have two object arrays that look like this: arr1 = [ { 'v1': 'abcde', 'pv_45': 13018, 'geolocation': '17.340291,76.842807' }] arr2 =[{ 'v1':'abcde', 'pv_50&apos ...

What is the best way to incorporate a .json configuration into the environment.ts file and access an API with Angular

I need to import a Json file from the assets folder containing URLs like the following: config.json: { "url1": "https://jsonplaceholder.typicode.com/posts", "url2" : "https://reqres.in/api/users", ...

Challenges with rendering text in Three.js

We are currently working on a project in three.js and facing difficulties when it comes to loading fonts onto our text elements. Our approach involves using the TextGeometry object for rendering fonts and the typeface js converter to incorporate new fonts ...

Prevent the opening of tabs in selenium using Node.js

Currently, I am using the selenium webdriver for node.js and loading an extension. The loading of the extension goes smoothly; however, when I run my project, it directs to the desired page but immediately the extension opens a new tab with a message (Than ...

What is the best way to retrieve a collection of DOM elements in JSX?

I'm in need of rendering certain components only if a specific condition is met. To achieve this, I have written the following inside the render() method: return ( <div className={classes.root}> {registrationScreen && ( * ...