Universal Vue.js application with Nuxt.js part#8 Learn how to write mapActions, Delete data from API, Delete data with Vuex
Repository
https://github.com/nuxt/nuxt.js
What Will I Learn?
- Learn how to write mapActions
- Delete data from API
- Process data with Vuex
Resources
- Nuxt.js Website - https://nuxtjs.org/
- Nuxt.js Github. - https://github.com/nuxt/nuxt.js
- Axios- https://github.com/axios/axios
- JSON Placeholder- https://jsonplaceholder.typicode.com/
- Vuex - https://github.com/vuejs/vuex
Difficulty
Intermediated
Tutorial Contents
In the previous tutorial, we have used mapActions()
to interact with actions in Vuex, there is another way of writing if you do not want to use mapActions like this ... mapActions()
, we will discuss writing mapActions in more detail. Then in if in the previous tutorial we have managed to submit data in this tutorial we will learn how to delete, edit data through the API that we provide, Then we will use the update and delete method on the API endpoint that we use, just start we learn.
How to write mapActions
There are two ways of writing mapActions that I have been using, one of which is that we have used in the previous tutorial, but I will explain it in more detail in this tutorial. I do not see any difference in the speed and memory side of this different way of writing, it just gives you a choice of which way is convenient for you to use.
1. Use ...mapActions()
We can use this way to shorten from the code side, but we also must first import mapActions like the example below.
Import mapActions:
import {mapActions} from 'vuex'
Const mapActions is a provision of Vuex ,you can not change it to your liking. After you import mapAction you can use it on property methods: {}
. Here is how to use it.
- Use in methods:
methods:{
...mapActions(['nameOfAction'])
}
Property methods contain the names of functions that usually feel from the event or user interaction with the application that we create. We can define the function we will use in ...mapActions()
by making it as a parameter. if you have many functions you can use arrays[] to separate names of other functions. for more details, there can see an example below
Example:
...mapActions(['function1', 'function2', function3'])
If we define a function in the manner described above, it means that the function name that exists in the component and the function name that exist in the Vuex actions must be the same. if not then Vuex will not recognize the function.
- parameter mapAction as object
If you want to give a different function name in Vuex you can initialize it as an object like following.
Example:
...mapActions({add : 'added'})
We pass as object and this example is add
is a function that exists on component and added
is the function in Vuex action. for more details, you can see the picture below
2. Use dispatch()
We can also directly access the action in Vuex through $store.dispatch()
, but we need an event to run this function when the user clicks the button, we will create a function that add()
we will put on the properties methods: {}
, for more details we can see in the example below.
Example:
methods:{
add (formData){
this.$store.dispatch('added',formData);
}
}
to access $store
we can use this
, then we will pass formData to be forwarded to the parameter in dispatch()
. the dispatch function has 1 mandatory parameter that is the name of the function to be run and the second parameter is optional, in this tutorial, we pass input data that we input in an object that is formData. If we look at the picture below below, the result will not be much different with the first way just a different way of writing.
and the following is the data that has been added to our database localhost: 3000/country
Delete data
If in the previous tutorial we have learned to submit data to the endpoint API, this time we will do the delete method on our data. Because we will delete so we need to pay attention to the API endpoint that we will use as shown below.
as we see in the picture, we need the ID of the data that we will delete. But before that I will provide the delete button so the user can click on the button.
- Add button and Action delete
We will add a button and make the @click
event on the button to call the delete function, for more details you can see the code below.
Example:
<div class="alert alert-primary" role="alert" v-for="item in countries" :key="item.id">
<p>Country : {{item.name}}</p>
<p>Capital City: {{item.city}}</p>
<button class="btn btn-danger" @click="doDelete(item.id)">Delete</button>
</div>
I will create a delete()
function and I pass that id to iteration item in countries so now we can take id through item.id
.
- Create function
delete()
We will make the delete function as below, later this function will delete data based on the id that has been passed in the @click="doDelete(item.id)"
.
Example:
methods:{
doDelete(id){
console.log(id);
}
}
Before we request the API, we must make sure that the ID has been successful obtained, I do console.log(id)
to prove it. for more details you can see the picture below.
after we get the ID of each data, we will call the function in action vuex, as we have learned we can access the action vuex with $store.dispatch
.
Dispatch 'deleteData':
doDelete(id){
this.$store.dispatch('deleteData',id);
}
We pass id as the second parameter in the above dispatch function, then we will make the deleteData function in the action on vuex.
function deleteData in action vuex:
async deleteData ({commit}, id){
const res = await axios.delete('country/'+id);
commit('deleted', id)
}
We can see we make changes to the axios method, we add axios.delete()
to delete the data then the id we receive, we make it as parameter 'country/+id'
, After that we can commit to call mutations to change the data in the state, actually the data has been deleted at this stage but the data in the state has not changed, because only mutations that can change the state.
- Change the state data in mutations
Our last task is to change the existing data in the state, we will do a little trick to delete the existing data in the state, we will find the same id in the state, we have passed the id when commit ('deleted', id )
. For more details we can see the example code as follows.
Example:
deleted(state, id){
const target = state.countries.findIndex(p=> p.id === id)
state.countries.splice(target, 1)
}
- We can use javascript method that findIndex to find the same index in id parameter
findIndex(p => p.id === id)
then we save the result toconst = target
. - Then we can get rid of the data by accessing state.countries and doing
splice ()
method from javascript and passing the value of the id we keep toconst target
. If there is no error you can see the result as shown below.
We have learned how to mapActions and we can see we have successfully deleted the data through the API that has been provided. we also use vuex in the process. I hope you enjoy this tutorial, hopefully useful, thank you
Curriculum
Learn Nuxt#1 Nuxt structure, Global CSS, Request API
Learn Nuxt#2 Vuex in Nuxt.js, Classic Mode and Modules Mode
Learn Nuxt#3 Create components, Reusable components and Nuxt-link
Learn Nuxt#4 Dynamic components, Props, Transition page, Dynamic pages
Learn Nuxt#5 Create Database API, Request data, Setup Port
Learn Nuxt#6 Create Store in Vuex, Request data in Vuex, Data centralized
Learn Nuxt#7 mapActions, Submit data, Process data with Vuex
Thank you for your contribution.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Hey @duski.harahap
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!