B
B
BonBon Slick2019-08-29 08:35:30
JavaScript
BonBon Slick, 2019-08-29 08:35:30

State as objects?

There is a state list, everything is ok while it is one. Then bam, the second list appeared on the page, the 3rd, and so on. Naturally, since the lists are already different, it is necessary for them to initialize other states for them, but that's the trouble, more than 80% of the code is absolutely identical.
For example, the page has a list of comments and a list of photos for a product, or another list of TOP comments, recommendations, menu tabs, etc.
For example, in the state it will be everywhere

state {
   list: [],
}

The same applies to actions, mutations, getters.
For example
actions: {
 additemToList({state}, {item});
},
getters: {
   getListItemByKey({state}, {itemKey});
}

How would it be more correct to decompose this?
That is, we initialize the list modules
Store({
  modules:
    listA,
    listB,
});

In fact, the modules are completely identical due to abstraction, is it possible to somehow do something like this
class ListA extends AbstractList{}
class ListB extends AbstractList{}

AbstractList contains state, mutations, getters, action methods. Something like:
abstract class AbstractList{

object list = {};

 getList(){
  return this.list;
}

addItemToList(item){
  this.list.push(item);
}

}

This is a very rough example, where the Abstract list object contains the list state, the addItemToList action and the getList getter, though it is not clear how and where to push the mutator.
I also thought about the option, just initialize the generalized object and then throw what is needed into it.
Example
const abstractListActions = {
     addItemToList({commit}, {item}){
        commit('addItem', item); //  mutator trigger
     }
};

export default abstractListActions;

And than
const listAActions = {
     removeItemByUrl({commit}, {url}) { // custom list method
        commit('removeByUrl', url); //  mutator trigger
     }
};

export default listAActions.concat(abstractListActions);

I would like to use objects, but it's also not clear how reliable the second option is.
Someone 100% faced with this, how did you solve it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Arutyunov, 2019-08-29
@arutyunov

If I'm not mistaken, then in this example, a similar task is solved in vue.js: https://github.com/vuejs/vue-hackernews-2.0
Code snippet:

export function createStore () {
  return new Vuex.Store({
    state: {
      activeType: null,
      itemsPerPage: 20,
      items: {/* [id: number]: Item */},
      users: {/* [id: string]: User */},
      lists: {
        top: [/* number */],
        new: [],
        show: [],
        ask: [],
        job: []
      }
    },
    actions,
    mutations,
    getters
  })
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question