Translate

Wednesday 24 January 2024

Give an example usage of actions?167

 

Give an example usage of actions?

Here are two examples of how you can use actions in Vuex:

Example 1: Fetching and setting products asynchronously:

Component:

JavaScript

export default {
  methods: {
    loadProducts() {
      this.$store.dispatch('fetchProducts');
    },
  },
};

Action:


JavaScript

export default {
  fetchProducts({ commit }) {
    axios.get('/api/products')
      .then(response => {
        commit('setProducts', response.data);
      })
      .catch(error => {
        // Handle error and dispatch relevant mutation
        commit('setError', error.message);
      });
  },
};

Mutations:


JavaScript

mutations: {
  setProducts(state, products) {
    state.products = products;
  },
  setError(state, error) {
    state.error = error;
  },
};

Explanation:

  • The loadProducts method in the component dispatches the fetchProducts action.

  • The fetchProducts action makes an asynchronous API call to retrieve products.

  • If the call is successful, the action commits the setProducts mutation with the fetched products as payload, updating the state.

  • If there's an error, the action commits the setError mutation with the error message.

Example 2: Adding a product with validation and side effect:

Component:


JavaScript

export default {
  methods: {
    addProduct(name, price) {
      this.$store.dispatch('addProduct', { name, price });
    },
  },
};

Action:


JavaScript

export default {
  addProduct({ commit }, { name, price }) {
    if (!name || !price) {
      // Show validation error message
      return;
    }

    // Perform validation logic (e.g., check uniqueness)
    // ...

    // Make async API call to add product
    axios.post('/api/products', { name, price })
      .then(() => {
        commit('addProduct', { name, price });
      })
      .catch(error => {
        // Handle error and show message
      });
  },
};

Mutation:


JavaScript

mutations: {
  addProduct(state, product) {
    state.products.push(product);
  },
};

Explanation:

  • The addProduct method in the component dispatches the addProduct action with the product name and price as payload.

  • The action performs validation checks and, if valid, makes an asynchronous API call to add the product.

  • If the call succeeds, the action commits the addProduct mutation with the new product as payload, updating the state.

  • If there's an error, the action handles it and shows an error message.

These are just two examples, and the possibilities for using actions are endless. You can use them to handle any complex logic or asynchronous operation that needs to update the state, making your Vuex application more efficient and organized.

Remember, actions should always trigger mutations to update the state, not perform direct modifications. They offer great flexibility for handling the complexities of asynchronous operations and side effects while maintaining a clean separation of concerns in your Vuex code.

Feel free to ask if you have any further questions about specific types of actions or need help implementing them in your application!


No comments:

Post a Comment

Note: only a member of this blog may post a comment.