Sidney Sousa
Sidney Sousa

Reputation: 3584

How can I return the data as multiple objects?

I set an empty array inside a state

const state = {
    jobs: []
}

Inside the component, I dispatch an action and the code looks like this:

created(){
    this.$store.dispatch('viewJobs');
}

The viewJobs actions looks like the following:

viewJobs: ({commit}) => {

    axios.get('/api/jobs')
        .then(res => {
            const jobss = res.data;

            console.log(jobss);

            commit('LIST_JOBS', jobss);

        })
        .catch(error => console.log(error));   
}

And then the mutations looks like this:

'LIST_JOBS'(state, jobss){
    state.jobs.push(jobss);
}

From the laravel side, my controller looks like this:

    $jobs = Employment::all();

    return $jobs->toJson(JSON_PRETTY_PRINT);

When I load the page, am able to console log jobss, but the state does not get updated.

How can I successfully push the data to the state?

Upvotes: 0

Views: 52

Answers (2)

Sabee
Sabee

Reputation: 1811

Try to use response()->json()

return response()->json(Employment::all(),200);

and try use {jobss:jobss} in commit section

viewJobs: ({commit}) => {

    axios.get('/api/jobs')
        .then(res => {
            const jobss = res.data;

            console.log(jobss);

            commit('LIST_JOBS', {jobss:jobss});

        })
        .catch(error => console.log(error));   
}

Another way, your vuex store looks like this

// state
export const state = () => ({
    items: []
})

// getters
export const getters = {
    items: state => state.items
}

// mutations
export const mutations = {
    SET_ITEMS (state, { items }) {
        state.items = items
    },
    PUSH_ITEM (state, { item }) {
        state.items.push(item)
    },
    UPDATE_ITEM (state, { index, item }) {
        state.items[index] = item
    },
    DELETE_ITEM: (state, index) => {
        state.items.splice(index.index, 1);
    }
}

// actions
export const actions = {
    setItems ({ commit }, { items }) {
        commit('SET_ITEMS', { items })
    },
    pushItem ({ commit,state }, { item }) {
        commit('PUSH_ITEM', { item })
    },
    deleteItem ({ commit,state }, { index }) {
        commit('DELETE_ITEM', { index })
    },

    updateItem ({ commit,state }, { index,item }) {
        commit('UPDATE_ITEM', { index,item })
    },
}

Then in your component call your action

 this.$axios.$get('/api/jobs')
        .then(res => {
            const jobss = res.data;

            console.log(jobss);

            this.$store.dispatch('your_store_name/setItems', {items:jobss});

        })
        .catch(error => console.log(error));

Upvotes: 1

levi
levi

Reputation: 25071

You are adding the entire array as a single element of state.jobs. Instead, you can use the Javascript spread operator, to push each element from the array:

state.jobs.push(...jobss)

Upvotes: 1

Related Questions