How to redirect in Nuxt's asyncData

Viewed 3010

I'm new to the vue.js and I have a simple question.

I have a code like below:

  asyncData({ params, error }) {
    return Job.api()
      .fetchByID(params.id)
      .then((response) => {
        const selectedJob = response.entities.jobs[0]
        if (selectedJob) {
          const industryID = selectedJob.industryId
          return Industry.api()
            .fetchByID(industryID)
            .then((result) => {
              const jobInd = result.response.data
              return {
                tagsArray:
                  selectedJob.tags === 'null' || selectedJob.tags === ''
                    ? []
                    : selectedJob.tags.split(','),
                job: selectedJob,
                jobIndustry: jobInd,
              }
            })
            .catch(() => {
              error({
                statusCode: 404,
                message: 'Job Industry not found',
              })
            })
        }
      })
      .catch(() => {
        error({
          statusCode: 404,
          message: 'Job not found',
        })
      })
  },

I want to know how should I redirect the page to the home page after catching the error 404.

2 Answers

asyncData()'s argument is the Nuxt context, which includes redirect() that you can use to redirect the user:

export default {
  asyncData({ redirect, params, error }) {
    return Job.api()
      .fetchByID(params.id)
      .then(/*...*/)
      .catch(() => {
        redirect('/')
      })
  }
}

You can redirect user programmatically to another page like that:

this.$router.push({ name: 'home' })

or

this.$router.push('/')

Notice: First example using name is better way than hardcoded path Example:

.catch((error) => {
    error({
      statusCode: 404,
      message: 'Job not found',
    })
   this.$router.push({ name: 'home' })
  })
Related