Introduction To VueX

Introduction To VueX

ยท

3 min read

VueX is a state management pattern and library for vue applications. Just like other state management libraries it provides a centralized store where all shared component states are stored.

VueX provides a simple application architecture and design.

Why use Vuex?

when building applications that require sharing of data and state within components, it can be tiresome to pass states and data from parent component to child components through prop drilling.

It can also become difficult to debug and maintain, for this purpose we need a centralized store where we can easily retrieve states and data independently within components and make the application more organized.

This is why we use a state management tool such as Vuex for vue applications.

Mutations.

How do we modify the data stored in the stores state?

Many at times we will need to modify or alter the application state in the store and we cannot do it directly. Since we cannot change the state directly, we will need to use mutations for this purpose.

Mutations allows us to write functions to alter data in the store.

We can do so as follows:

Example:

mutations: {
    // mutate the photos array here
    addPhotos(state,photos){
        state.photos.push(photos)
    }
}

Getters.

How do we get the data stored in the stores state?

The best way to retrieve application state from the store object is via the use of getters. Getters are pure functions which return a read-only copy of the desired data.

Getters also allows for accessing filtered, derived or computed state.

Example:

getters:{
  // get photos array
  getPhotos(state){
    return state.photos;
  }

}

Actions.

How do we commit mutations?

Actions are essentially methods that commit mutations. Actions also enables our mutations to have some logic.

The code above will fetch car photos from the endpoint and commit it to the getPhotos mutations.

This is a simple way to commit a method to mutations

Example:

actions:{
  async getcarPhotos({ commit }) {
      const response = await fetch("https://api.pexels.com/v1/search?query=car");
      const data = await response.json();
      commit("getPhotos", data);
    }

}

Conclusion

Vuex provides for a centralized and organized application state storage. It also ensures easy readability of our code.

By ensuring an organized application and state structure, it ensures that our application is easy to understand and avoids the effects of prop drilling from parent to child components.

Just to recap we have learnt:

  • How to manipulate state through mutations?
  • How to get data stored in states using getters?

If you found this article helpful, please share and subscribe to my newsletter you will be notified every time I publish a new article like this.

You can also keep in touch on this platforms:

Twitter | LinkedIn| YouTube| GitHub

Until next time PEACE!

ย