Search code examples
javascriptvue.jsfetchvuex

Vue, fetch returns empty array


I'm fetching some data in my vue-cli project.

I'm using Vuex to store the data.

It all runs successfully apart from the fact that I get an empty array, I have checked in Postman, and it works perfectly.

As you can see in my actions i had my commit in the if statement, currently commented out and moved. But when run in there I get a Promise returned. And as the current edition of my code I get an empty array.

I really cant see what my error is, so my best bet is you guys are able to see what I'm missing.

First I have my actions:

export default {

async getProLanguages({ commit }) {
    commit(C.PROLANGAUGE_DATA_PENDING);
    try {
        const res = await fetch('https://dev-webapp-kimga5xexrm3o.azurewebsites.net/api/ProLang', {
            method: 'GET',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Authorization': 'Bearer xxx'
            }
        });
        if (res.status === 200) {
            console.log(res);
            // commit(C.PROLANGAUGE_DATA_SUCCESS, JSON.stringify(res.json()));
        }
        else {
            commit(C.PROLANGAUGE_DATA_NO_CONTENT);
        }
        console.log(res)
        return commit(C.PROLANGAUGE_DATA_SUCCESS, JSON.stringify(res.json()));
    }
    catch (e) {
        commit(C.PROLANGAUGE_DATA_FAILURE);
    }
}

And my mutations:

 /**
 *  Indicates that programming language has succeded 
 * 
 * @param state 
 * @param  payload 
 */
[C.PROLANGAUGE_DATA_SUCCESS](state, payload) {
    state.programmingLanguages = { ...state.programmingLanguages, loading: false, error: false, noContent: false, items: payload }
},

And I have my default state, which is imported into state.js:

const getDefaultState = () => ({
  programmingLanguages: {
    loading: false,
    error: false,
    noContent: false,
    items: [
      {
        id: undefined,
        name: undefined
      }
    ]
  }
});

I call my action with a beforeRouteEnter:

beforeRouteEnter(to, from, next) {
  store.dispatch('programmingLanguages/getProLanguages').then(() => {
    next();
  });
}

and finally in my component I import mapState from Vuex:

computed: {
  ...mapState({
    prolangs: state => state.programmingLanguages.programmingLanguages.items
  })
}

Solution

  • I think something like items = await res.json(), then committing items could be a way forward (make sure all promises are resolved).