0

I create 2 projects - 1 for backend and 1 for frontend with Laravel and VueJS. From Laravel i create API endpoint for all users:

Laravel routes/api.php

Route::prefix('users')->group(function(){
    Route::get('all', [UsersController::class, 'index']);
});

Here is UsersController

public function index(){
        $user = User::select('id','name', 'email')->get();

        return response()->json($user);
    }

and this is what i received from api with Postman:

[
    {
        "id": 1,
        "name": "Toni Stoyanov",
        "email": "[email protected]"
    },
    {
        "id": 2,
        "name": "Thomas Shelby",
        "email": "[email protected]"
    }
]

And this is my VueJS files:

axios.defaults.baseURL = 'http://backend.test/api/'

and in my Vuex i made folder users/index.js

import axios from 'axios'

export default {
    state(){
        return{
            users: {

            }
        }
    },
    getters:{
        getUsers(state){
            return state.users
        }
    },
    mutations:{
        SET_USER(state, data){
            state.users = data
        }
    },
    actions:{
        async setUsers(context){
            let response = await axios.get('users/all')
            console.log(response)
    
            context.commit('SET_USER',response.data)
        }
    }
}

and in my component with computed property:

getUsers(){
            return this.$store.getters.getUsers
        }

And nothing come into my app..When i fill users with some dummy data getter works, but actions and mutations doesnt work.

1 Answer 1

2

You've to dispatch the action in created hook :

computed:{
getUsers(){
            return this.$store.getters.getUsers
        }
},
created(){
   this.$store.dispatch('setUsers')
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.