Search code examples
javascriptvue.jsvuexvuex-modules

Why does getter not return the value


I have a getter that returns array of objects. The porblem is that I need past and actual warnings in different components.

It return only actual warning and ignoring past. But when I removing the map method it works correctly.

P.S I tried to split this getter in two getters

getPastOrActualWarnings: state => type => {
    const now = +new Date()
    let warnings
    if (type === 'actual') {
        warnings = state.warnings.filter(item => item.time * UNIX_TIMESTAMP > now)
    } else if (type === 'past') {
        warnings = state.warnings.filter(item => item.time * UNIX_TIMESTAMP < now)
    } else {
        warnings = []
    }

    return warnings.map(dateToString)
}

function dateToString (item) {
    item.time = new Date(item.time * UNIX_TIMESTAMP).toLocaleDateString('ru-RU', DATE_OPTIONS)
    return item
}

Solution

  • The problem is that you are modifying the state directly with your getter, which is something you should never do. The following line modifies item.time, which you previously used to sort the items. item is a reference to the object that is stored in the state.

    item.time = new Date(item.time * UNIX_TIMESTAMP).toLocaleDateString('ru-RU', DATE_OPTIONS)
    

    To solve the issue, you can do one of two things:

    • Use a different name for your rendered time

      item.renderedTime = new Date(item.time * UNIX_TIMESTAMP).toLocaleDateString('ru-RU', DATE_OPTIONS)
      
    • (Shallow) copy the item so you are modifying a local copy, rather than the one in the state

      function dateToString(item) {
        const localItem = { ...item };
        localItem.time = new Date(item.time * UNIX_TIMESTAMP).toLocaleDateString(
          "ru-RU"
        );
        return localItem;
      }