how to get formatted response payload on api call - vue

Viewed 119

I am using multiple dropdown list and fetching the data based on url. There are two dropdowns like below.

 1 . data: [{"id": 1, "value":"Shoe"},{"id": 2, "value":"Clothing"}] --> categories 
        url  -> '/api/products/category'
 2. data : [{ "category_name": "Shoe", sizes: ['7','8','9'] }] --> available sizes
        url -> '/products/${item_id}/category/${category_id} 

Now, i am using service and vuex action to load dropdown based url.

Here is service

    export async function fetchItemsOfDrowdown(url) { // passing the url 
    const resp = await http.get(url);
    return resp.data;
}

Here is the action

    async fetchDropdownItems({ state, commit }, payload) {
    if (!state.fieldItems[payload.key]) {
        const items = await service.fetchItemsOfDrowdown(payload.url);
        const parsedItems = [];
        for (let i = 0; i < items.length; i += 1) {
            const item = items[i];
            parsedItems.push({
                text: item[payload.text],
                value: item[payload.value]
            });
        }
        commit('DropdownFieldItems', {
            key: payload.key,
            items: parsedItems
        });
    }
}

Mutation

DropdownFieldItems(state, payload) {
    state.fieldItems = {
        ...state.fieldItems,
        [payload.key]: payload.items
    };
}

How i am configuring dropdown fields type

fields : {
    category_id: {
        key: 'category_id',
        label: 'Category',
        uri: '/products/category',
        value: '',
        items: []
    },
    product_size: {
        key: 'product_size',
        label: 'Available Size',
        value: '',
        uri: '/products/${item_id}/category/${category_id}
        items: []
    }
   }

Calling the action into action and passing the data like this

created() {
    if (this.fields && Object.keys(this.fields).length > 0) {
        const fieldKeys = Object.keys(this.fields);
        for (let i = 0; i < fieldKeys.length; i += 1) {
            const key = fieldKeys[i];
            if (this.fields[key] && this.fields[key].uri) {
                this.fetchDropdownItems({
                    key,
                    url: this.fields[key].uri,
                    text: 'value',
                    value: 'id'
                });
            }
        }
    }
},

I want to store dropdown fields into state like this.

payload: object --> items: Array[2] key --> "category_id" --> for 1st one working fine

I want to format the 2nd url payload so we can store it as same as 1st one. How to format the 2nd payload structure like 1st one in action itself?

0 Answers
Related