Search code examples
vue.jsvuejs2vue-componentnuxt.jsvue-router

How to redirect in Nuxt's asyncData


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.


Solution

  • 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('/')
          })
      }
    }