user3640511
user3640511

Reputation: 177

Component not re-rendering when state is updated

I've been trying to debug this but for some reason when I pull data from an external API in the created lifecycle function and update the store with a mutation, the component's computed property that is getting the state doesn't seem to update which leads to the component not re-rendering. Any ideas?

Here is the template for the component:

<template>
    <div class="list">
        <ul>
            <ListItem v-for="transaction in transactions" :list-item-data="transaction" :key="transaction.txid"/>
        </ul>
    </div>
</template>

<script>
    import ListItem from './ListItem.vue';
    import External from '../ExternalAPI';

    export default {
        methods: {
            fetchData() {
                return ExternalAPI.fetch(data => {
                    this.$store.dispatch('setTransactions', data);
                });
            }
        },
        components: {
            ListItem
        },
        computed: {
            transactions () {
                return this.$store.getters.transactions;
            },
        },
        created() {
            this.fetchData();
        },
    }
</script>

Here is the store:

export const store = new Vuex.Store({
    state: {
      transactions: [],
    },
    getters: {
      transactions: state => {
        return state.transactions;
      }
    },
    mutations: {
      setTransactions: (state, transactions) => {
        let txs = transactions.map(transaction => {
            return new Transaction(transaction.id, transaction.prop1, transaction.prop2);
        });
        state.transactions = txs;
      },
    },
    actions: {
      setTransactions: (context, transactions) => {
        context.commit('setTransactions', transactions);
      },
    },
});

Upvotes: 2

Views: 621

Answers (1)

psalaets
psalaets

Reputation: 717

Anything in the vuex state tree needs to be a primitive, plain object or an array. I can't find anything in the docs explicitly saying that but I did find a comment on vuex issue 153.

You're instantiating some Transaction in your setTransactions mutation. Try changing that to something like

setTransactions: (state, transactions) => {
  let txs = transactions.map(transaction => {
    return {
      id: transaction.id,
      prop1: transaction.prop1,
      prop2: transaction.prop2
    };
  });
  state.transactions = txs;
},

Upvotes: 1

Related Questions