Search code examples
javascriptvue.jsvuex

Vuex set state object default as object in array in state


If I have in my store:

 state: {
     items: [],
     currentItem: {}
 }

and I want to select the first item on array as default currentItem:

 state: {
    items: [],
    currentItem: state.items[0]
 }

Which can't be done as state is undefined inside state. I know that state has to be changed with a mutation. But if the state was a boolean I could set it for instance to false as default.

Is there a way to make it similar to the way I tried above?


Solution

  • This is a common JavaScript problem. It's not possible to refer to a property of an object that wasn't defined yet.

    This requires to have temporary variable that stores a reference to reused object:

    const items = [/*...*/];
    
    ...
     state: {
         items,
         currentItem: items[0]
     }
    

    This can be done in-place in less readable way with IIFE if the context isn't suitable for temporary variables:

     ...
     state: (items) => ({
         items,
         currentItem: items[0]
     })([/*...*/])