Home > OS >  Fetch hook based on router params doesn't work on page refresh
Fetch hook based on router params doesn't work on page refresh

Time:10-18

I fetch property data through params. In this property data are ID's of agents located. So, after successfully fetching the property data, I want to fetch the agents data through the just received ID's. The problem, if I manually refresh the page, the agent data isn't fetching. If I enter the page through the app navigation, it will.

Why is that? Or do I have to change something in the structure of how I fetch the data?

async fetch() {
  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.getAgents(agentIDs)
    }
  } catch (err) {
    console.log(err)
  }
},
methods: {
  async getAgents(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)
    }
  }
}

CodePudding user response:

You should probably await your method with the following

await this.getAgents(agentIDs)

The rest looks fine!

CodePudding user response:

Using SSR fetch() is run by default on serverSide

  • if You specify fetchOnServer: false then it's only happening on clientSide

@PhilippeUn it could be cleaner to use async/await syntax instead of try/catch. But for sure easier to resolve the both of APIs call in fetch hook. (Then always You can use this.$fetch() and it'll re-run the hook.)

  • it allows to use the $fetchState.error/pending state

  • Just a hint to stop using console.log for error, try to use console.error as it makes trace of the errors.

But my main concern is that there's used $POST method to GET data? Use GET for requesting data

I understand that by POST You can use BODY in the request but it makes a lot of risks for the backend.

  • Related