Search code examples
vue.jspinia

How to call Pinia action from another action?


Is there a way to call Pinia store action from another action in the same store? For example, I have Pinia store like this:

export const useCounter = defineStore({
    id: 'counter',

    state: () => ({
        counter: 0
    }),

    actions: {
        addOne() {
            this.state.counter++
        },
        addTwo() {
            // Can i call here addOne action?
            // Things like this not working:
            this.addOne();
            this.addOne();
            // This is not working too:
            this.actions.addOne();
            this.actions.addOne();
        }
    }
});

Can I call AddOne action inside addTwo?


Solution

  • You can indeed access methods of the same store by this. Just used it in my own store's action method. The getPost action method is accessing multiple methods of the same store through this (checkPost, fetchPost) and it works just fine.

    import {defineStore} from 'pinia';
    import axios from 'axios';
    const axiosInstance = axios.create({
        baseURL: window.wue.restUrl,
    })
    
    export const useBlogStore = defineStore(
        'blog',
        {
            state: () => ({
                posts: [],
    
            }),
            getters: {
                postCount(state) {
                    return state.posts.length;
                },
                checkPost(state) {
                    return (property, value) => (state.posts.find(post => post[property] === value));
                }
            },
            actions:{
                addPost(post) {
                    this.posts.push(post)
                },
                async getPost(property, value) {
                    if (this.checkPost(property, value)) {
                        return this.checkPost(property, value);
                    } else {
                        return this.fetchPost(property, value);
                    }
                },
                async fetchPost(property, value) {
                    try {
                        let json;
                        if (property === "slug") {
                            json = await axiosInstance.get(`posts?slug=${value}`);
                        } else if (property === "id") {
                            json = await axiosInstance.get(`posts/${value}`);
                        }
                        const post = json.data[0];
                        this.addPost(post);
                        return post;
                    } catch (error) {
                        alert(error);
                        console.log(error);
                    }
                },
         }
    });