Nuxt js Router Push Not Working After Delete

Viewed 373

I've created a simple CRUD with Nuxt. Data is provided by Lumen. I got a problem with the DELETE, data is deleted but Nuxt does not redirect to the other page.

Here is my script:

<script>
export default {
  name: 'EmployeePage',
  data() {
    return {
      fields: ['name','email','image','address'],
      emplyees:[],
    }
  },
  mounted() {
    this.$axios.get('/employee').then(response => {
      this.pegawais = response.data.data
    }).catch(error => {
      console.log(error.response.data)
    })
  },
  methods: {
    async delete(id) {
      await this.$axios.delete(`/employee/${id}`).then(response => {
        this.$router.push({ name: 'employee' })   <-----this redirect not working
      })
    }
  }
}
</script>

I want Nuxt to redirect to the employee page that display all the data after the deletion.

1 Answers

You should not mix async/await and .then. Use the first approach, that way you will not have the .then callback hell and it will be cleaner overall.

Like this

<script>
export default {
  name: 'EmployeePage',
  data() {
    return {
      fields: ['name', 'email', 'image', 'address'],
      emplyees: [],
    }
  },
  async mounted() {
    try {
      const response = await this.$axios.get('/employee')
      this.pegawais = response.data.data
    } catch (error) {
      console.log(error.response.data)
    }
  },
  methods: {
    async delete(id) {
      await this.$axios.delete(`/employee/${id}`)
      await this.$router.push({ name: 'employee' })
    },
  },
}
</script>

await this.$router.push does not require an await but it's a Promise too, so I'm writing it like that in case you need to call something else afterwards.


this.$axios.$get('/employee') can also be used if you want to remove a .data aka this.pegawais = response.data as shown here.

Related