Nuxt - VueX plugin mutation doesn't update state

Viewed 37

I created a plugin for Vuex on my Nuxt app.
The plugin should update the state with a payload from the localStorage.

Here is my plugin code:

import { Store } from 'vuex';

export const localStoragePlugin = (store: Store<any>) => {
  // called when the store is initialized
  let invitationState = '';
  if (process.client) {
    invitationState = localStorage.getItem('invitation');
  }

  if (invitationState) {
    // Replace the store state object with the stored object
    store.dispatch('invitation/setInvitation', JSON.parse(invitationState));
  }

  store.subscribe((mutation) => {
    // called after every mutation.
    // The mutation comes in the format of `{ type, payload }`.
    if (process.client) {
      localStorage.setItem(mutation.type.split('/')[0], JSON.stringify(mutation.payload));
    }
  });
};

On store initializing I get the cont from the localStore and then I mutate the content to the state.
The subscribe part is in charge on update the localStorage in case of a new mutation.

This is my store definition:

import { Invitation } from '@/interfaces/graphql/types';

export const state = (): Invitation => ({
  id: null,
  email: null,
  toProfile: null,
  fromProfile: null,
  inviteSource: null,
});

export const mutations = {
  SET(state: Invitation, payload: Invitation) {
    console.log('mutation SET');
    const { id, email, toProfile, fromProfile, inviteSource } = payload;
    state.id = id;
    state.email = email;
    state.toProfile = toProfile;
    state.fromProfile = fromProfile;
    state.inviteSource = inviteSource;
  },
};

export const actions = {
  setInvitation({ commit }, invitation) {
    console.log(invitation);
    commit('SET', invitation);
  },
};

export const getters = {
  invitation(state: Invitation) {
    return state;
  },
};

The console log inside the mutation is printed but I don't have any mutation on the Vue developer tool and the state is empty.

enter image description here

What am I doing wrong?

0 Answers
Related