Giter Site home page Giter Site logo

danielroe / typed-vuex Goto Github PK

View Code? Open in Web Editor NEW
352.0 6.0 27.0 9.33 MB

🏦 A typed store accessor for vanilla Vuex.

Home Page: https://typed-vuex.roe.dev

License: MIT License

JavaScript 4.95% TypeScript 91.48% Vue 3.18% Shell 0.39%
vuex nuxt typescript vue vuejs nuxtjs nuxt-module hacktoberfest

typed-vuex's Introduction

🏦 Typed Vuex

A strongly-typed store accessor for vanilla Vuex

Read documentation

Summary

This module provides a store accessor and helper type methods so you can access your vanilla Vuex store in a strongly typed way.

Image showing autocomplete on this.$accessor

Image showing autocomplete on commit within store

Note: This has been developed to suit my needs but additional use cases and contributions are very welcome.

MIT License - Copyright Β© Daniel Roe

typed-vuex's People

Contributors

andrewvasilchuk avatar bazuka5801 avatar danielroe avatar daniluk4000 avatar dependabot[bot] avatar florian-lefebvre avatar moajo avatar renovate[bot] avatar solant avatar sugarf0x avatar tahul avatar toomuchdesign avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

typed-vuex's Issues

docs: How do I reference $accessor inside a store's action tree?

How do I correctly reference $accessor inside a store's action tree?

This works:

store.ts

export const actions = actionTree(
  { state, getters, mutations },
  {
          this.app.$accessor.foo.bar()

    },

.. but getting type error: TS7022: 'actions' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

vue-shim.d.ts

declare module '@nuxt/types' {
  interface NuxtAppOptions {
    $accessor: typeof accessorType
  }
}

TS2502: '$accessor' is referenced directly or indirectly in its own type annotation.

quest: How to set up multi-level module

How to set up multi-level moudle?

rootVuex:{
  ui:{
    left:{

    }
  },
  user:{}
}
import * as user from './user';
import * as ui from './ui';
import * as left from './ui/left';

how to set the left module ?

fix: Error: Cannot find module './utils'

πŸ› The bug
I am getting the following issue while running npm run dev:

error

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

  1. Install [email protected] , @nuxt/typescript-build, '@nuxt/typescript-runtime`
  2. run npm run dev
  3. See error in console

🌈 Expected behaviour
Project should boot up without the exception.

ℹ️ Additional context
Everything seems okay with 0.1.13.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (:automergeEarlyMondays). Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

docs: How to use "this.app.$accessor" in getterTree ?

πŸ“š Is your documentation request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I feel I should be able to [...] but I can't see how to do it from the docs.

πŸ” Where should you find it?
What page of the docs do you expect this information to be found on?

ℹ️ Additional context
Add any other context or information.

docs: How to properly use generics

I am newbie to typescript. But how to achieve my goal with mutations?

I want to reproduce code from here:
keyof

[MutationTypes.SET_USER_PROPERTY]<T, K extends keyof T["User"]>(state: T, payload: { key: K, value: T[K] }): void {
  state.user[key] = value
}

docs: combine nuxt-composition-api and nuxt-typed-vue

πŸ“š Is your documentation request related to a problem? Please describe.

Hi does nuxt-typed-vuex and nuxt-composition-api work together out of the box.
Do you have any example repo where these two are used together?

Thanks in advance!

docs: how to mock app in actions

As I understand it you're supposed to use this.app to reference other modules in actions (ie this.app.$axios). In unit tests I keep getting a "Cannot read property '$axios' of undefined" message for my action code:

const workspaces: Array<Workspace> = await this.app.$axios.$get(
          'https://example.com',
          {
            auth: apiLogin,
          }
        )

The factory method I use to test the store:

function factory({ promise = Promise.resolve({}) as Promise<any> }) {
  jest.mock('axios')
  const mockNuxtAxios = axios as jest.Mocked<NuxtAxiosInstance>
  mockNuxtAxios.$get = jest.fn().mockReturnValue(promise)

  const localVue = createLocalVue()
  localVue.use(Vuex)

  const store = new Vuex.Store({ state, mutations, actions, getters })

  return useAccessor(store, {
    state,
    mutations,
    actions,
    getters,
  })
}

Is there an easy way to do something like

actions.app = {$axios: mockNuxtAxios}

fix: Cannot set property application of #<Object> which has only a getter

πŸ› The bug

The app breaks at lunch.

πŸ› οΈ To reproduce
Creating a project with yarn create nuxt-app someapp and installing nuxt-typed-vuex. After adding it to the build modules, when launching the app it shows the black loading spinner and in the console it says:

TypeError: Cannot set property application of #<Object> which has only a getter
    at eval (index.es.js?9e80:53)
    at Array.forEach (<anonymous>)
    at createAccessor (index.es.js?9e80:52)
    at useAccessor (index.es.js?9e80:58)
    at eval (index.es.js?9e80:61)
    at Array.forEach (<anonymous>)
    at useAccessor (index.es.js?9e80:59)
    at eval (index.es.js?9e80:66)
    at _callee$ (nuxt-typed-vuex.js?679e:8)
    at tryCatch (runtime.js?96cf:63)

I've tried many things, I'm using the helper functions in every module, I even sent and empty getAccessorType({}) and it stills shows the error in the console. It only disappears when removing the nuxt-typed-vuex from the buildModules.

🌈 Expected behaviour
It should not show any error.

ℹ️ Additional context
It is the only buildModule I'm using aside from '@nuxt/typescript-build' and '@nuxtjs/vuetify' that come with the installation.

[FEATURE] Add nuxt-typed-vuex on Context API

There's no format for how I can create an Issue.

say. I want to use the $accessor in the asyncData.

 async asyncData({$accessor}) {
    console.log($accessor) // output: undefined
 },

it turns out. when I tried to check the context. the $accessor is accessible in context.app.$accessor

  async asyncData({app}) {
    console.log(app.$accessor) // Will list all registered store in Vuex
   //console.log(store.$accessor) // this will also work
  },

It does solved my problem when accessing $accessor from the asyncData, but I don't know how to put the $accessor to the Context API in the index.d.ts file(provided from your example).

access this.$axios from an action

Hi, I'm trying to use this.$axios inside an action but I get the error Property '$axios' does not exist on type 'Store<ArticleState>', do you know if it's a bug or if I'm missing something?

devtools vuex not working

πŸ› when using vueDevTools vuex not update correctly
we are using your package but when vuex updated the state data did'nt update in vueDevTools

docs: how do I use it without nuxt?

As I understood, this library can be used without Nuxt.js(or not?). Because library exposes useful helpers like getAccessorType, useAccessor. So we can create accessors (just a simple proxy) wherever we want? It would be great to add some docs about usage in projects scaffolded with Vue CLI (etc.).

Maybe I am wrong and it can not be used without Nuxt.js? Can you correct me?

docs: How to use other modules?

How to use other modules?

// store/index.ts
import * as user from './user'

export const state = () => ({
  device: 'mobile'
})

export const getters = getterTree(state, {
  isMobile: (state) => state.device === 'mobile'
})

export const mutations = mutationTree(state, {
  setDevice(state, newValue: string) {
    state.device = newValue
  }
})

export const actions = actionTree(
  { state, getters, mutations },
  {
    async nuxtServerInit(vuexCxt, nuxtCxt: Context) {
      // Error: Argument of type '"user/info"' is not assignable to parameter of type 'never'.ts(2345)
      vuexCxt.commit('user/info', { name: 'xxx' })


      // Error: 'actions' implicitly has type 'any' because it does not have a type annotation
      // and is referenced directly or indirectly in its own initializer.ts(7022)
      // Error: 'accessorType' implicitly has type 'any' because it does not have a type annotation
      // and is referenced directly or indirectly in its own initializer.ts(7022)
      this.app.$accessor.user.info({ name: 'xxx' })
    }
  }
)

export const accessorType = getAccessorType({
  actions,
  getters,
  mutations,
  state,
  modules: { user }
})
// index.d.ts
import { accessorType } from '~/store'

declare module 'vue/types/vue' {
  interface Vue {
    $accessor: typeof accessorType
  }
}

declare module '@nuxt/types' {
  interface NuxtAppOptions {
    // If used: vuexCxt.commit('user/init')
    // Error: '$accessor' is referenced directly or indirectly in its own type annotation.ts(2502)
    $accessor: typeof accessorType
  }
}

support for @nuxt/typescript-runtime

πŸ› The bug
If you use @nuxt/typescript-runtime and write your Nuxt configuration in TypeScript (nuxt.config.ts), nuxt-typed-vuex will break in a weird way with pretty much no context or way to debug the issue (see screenshot below)

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

  1. follow instructions on the Nuxt TypeScript documentation page to set up typescript-runtime and write your config in TypeScript
  2. Install and set up nuxt-typed-vuex
  3. Run the development server (nuxt-ts)
  4. See error: Unexpected Identifier

ℹ️ Additional context
Screenshot 2019-11-07 at 11 57 26

The exact same configuration, written in JavaScript will work as expected.

Not sure if this relates to nuxt-typed-vuex or Nuxt itself, but leaving it here for someone with more info about how these libraries work together to inspect this further.

fix: state objects don't work with submodules

πŸ› The bug
I get the following issue during invocation of useAccessor function.

const storePattern = {
  state,
  mutations,
  modules: {
    foo,
  },
}

const store = new Vuex.Store(storePattern)

export const accessor = useAccessor(store, storePattern)
Uncaught TypeError: Cannot set property foo of #<Object> which has only a getter

πŸ› οΈ To reproduce
Try to invoke useAccessor with any module, which state declared as plain object.

🌈 Expected behaviour
I expect the correct module registration.

ℹ️ Additional context
Add any other context about the problem here.

fix: Optional payload in action create necessary parameter

πŸ› The bug

export const actions = actionTree(
  { state, mutations, getters },
  {
    doSomething({commit}, payload?: string) { // optional parameter
      // ...do something
    }
  }
);

$accessor.login(); create typescript error

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

🌈 Expected behaviour
$accessor.login(); not to create ts error.

ℹ️ Additional context
Add any other context about the problem here.

Make clear that state, mutations and actions all should have different names

πŸ“š Is your documentation request related to a problem? Please describe.
I ran into the following error after migrating my store to typed-vuex:

Cannot set property connected of #<Object> which has only a getter

This error does not contain much detail and was quite hard to debug. I figured it was caused by having a mutation that is named the same as a state property. So I had state.connected and a connected mutation.
While I should've named my mutation setConnected and it is not common to have the same name for state and mutations or actions, it is something that works in plain vuex but is a limitation of typed-vuex.

It would be great if this would be noticed as a warning in the docs.

docs: (or issue?) make it work with nuxtServerInit

Is it possible to use nuxt-typed-vuex and nuxtServerInit action?
It seems the last is not triggered for me.
That's my index.ts file:

import { getAccessorType } from 'nuxt-typed-vuex'

import * as snack from './snack'
import * as ui from './ui'
...

export const state = () => ({})

export const actions = {
  nuxtServerInit (context1: any, context2: any) {
    console.log('nuxtserverinit run', context1, context2)
  }
}

export type RootState = ReturnType<typeof state>

export const accessorType = getAccessorType({
  state,
  actions,
  modules: {
    snack,
    ui
    ...
  }
})

Could you update the docs with nuxtServerInit usage?

Question: TS lint error when used with nuxt-ts

Hi:

My store looks like this store/index.ts:

export const state = () => ({
  version: DEFAULT_APP_VERSION as string,
  loggedIn: false,
  userId: null as number | null,
  userName: null as string | null,
  userIdentity: null as string | null,
  userRole: null as UserRole | null,
  userMunicipios: [] as string[],
  busy: false,
  lastRequestedPath: null as string | null
});

type RootState = ReturnType<typeof state>;

export const getters = getterTree(state, {
  getVersion: (state) => state.version,
  isLoggedIn: (state) => state.loggedIn,
  getUserId: (state) => state.userId,
  getUserName: (state) => state.userName,
  getUserIdentity: (state) => state.userIdentity,
  getUserRole: (state) => state.userRole,
  getUserMunicipios: (state) => state.userMunicipios,
  isBusy: (state) => state.busy,
  getLastRequestedPath: (state) => state.lastRequestedPath
});
...
...
export const accessorType = getAccessorType({
  state,
  getters,
  mutations,
  actions
});

I have the following on index.d.ts:

import { accessorType } from "@/store";

declare module "vue/types/vue" {
  interface Vue {
    $accessor: typeof accessorType;
  }
}

declare module "@nuxt/types" {
  interface NuxtAppOptions {
    $accessor: typeof accessorType;
  }
}

On my component layout/default.vue:

<script lang="ts">
import { defineComponent, computed, ref, reactive } from "@vue/composition-api";
export default defineComponent({
  name: "default",
  setup(_props, { root }) {
    const title = computed(() => root.$accessor.getVersion);
    const version = computed(() => root.$accessor.getVersion);
    const loggedIn = computed(() => root.$accessor.isLoggedIn);
    return {
      title,
      version ,
      loggedIn
    };
  }
});

eslint-error-2

yarn build (nuxt-ts build) and yarn dev (nuxt-ts) works but my IDE (Intellij 2020.2) shows previous error, how can I remove the error, any idea?

yarn --version: 1.22.4
node --version: v12.18.3
vue --version: @vue/cli 4.5.3
yarn list nuxt: [email protected]
yarn list @vue/composition-api: @vue/[email protected]

fix: Props couldn't use object alongside $accessor. Using array works

πŸ› The bug
What isn't working? Describe what the bug is.

I have a component that sends a simple Array/Object into its child component.
so that child component has a prop of Array/Object that needs to check its types.

export default Vue.extend({
  computed: {
    getDataFromStore() {
      return this.$accessor.getData(); // will throw error if props set to empty object
    },
  },
  async mounted() {
    try {
      await this.$accessor.fetchStore(); // will throw error if props set to empty object
    } catch (error) {
      this.$accessor.SET_ERROR(error) // will throw error if props set to empty object
    }
  },
  props:{} // doesn't work
 //prop:[] //it works
})

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

  1. Go to './store/index.ts'
  2. Create a simple vuex state
  3. call the getters and actions of the state
  4. add props to any component

🌈 Expected behaviour
What did you expect to happen? Is there a section in the docs about this?
I am able to send props to its child and alongside with having typed vuex
ℹ️ Additional context
Add any other context about the problem here.
I don't know what causes this error. I am not very familiar with Typescript's inferring types inside VSCODE.

fix: actions and accessorType is untyped when using nuxtServerInit()

Here's the reproduction link: https://codesandbox.io/s/elated-ives-x1hzb?file=/store/index.ts

Take a look at /store/index.ts file:

image

When i'm trying to use $accessor inside nuxtServerInit() then i'm gettin error about actions and accessorType - "
implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."

Actually what i'm trying to achieve here, is to fetch data, then commit it:

    async nuxtServerInit(_vuexContext, nuxtContext: Context) {
      const data = await nuxtContext.app.$api.calc.getOffers()
      const offers = data.bundles
      const services = data.services
      const selectedInternet = offers[0].selected
      nuxtContext.app.$accessor.calculator.setInternet(
        offers[0].availableBundles[selectedInternet]
      )
    },

Also what's the purpose of _vuexContext if we're using $accessor?

fix: `$accessor` object does not contain mutations

πŸ› The bug
The $accessor object contains state variables but no mutations

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

  1. Create a nuxt application and add some store variables with mutations.
  2. Access the $accessor via middleware's context.

🌈 Expected behavior
Typescript recognizes store mutations.

ℹ️ Additional context
Add any other context about the problem here.

fix: respect proto

πŸ› The bug
When state is an instance of a class, prototype chain is lost.

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

import Vue from 'vue'
import Vuex from 'vuex'

import { useAccessor } from 'typed-vuex'

class Car {
  constructor(public name: string) {}

  setName(value: string) {
    this.name = value
  }
}

const state = new Car('BMW')

const mutations = mutationTree(state, {
  mutation(state, name: string) {
    state.setName(name) // OK
  },
})

const storePattern = {
  state,
  mutations,
}

const store = new Vuex.Store(storePattern)

export const accessor = useAccessor(store, storePattern)

accessor.setName('name') // Error, prototype chain is lost

🌈 Expected behaviour
Prototype chain is preserved.

ℹ️ Additional context
Consider using Object.create here.

docs: Property '$accessor' does not exist on type

Hi, thanks for the very cool lib!

πŸ“š Is your documentation request related to a problem? Please describe.
After adding the lib to my nuxt Project and creating a index.d.ts file I get this error
Property '$accessor' does not exist on type 'CombinedVueInstance<Vue, object, object, object, Record<never, any>>'.

Do I need to import this file somewhere? I have a vue-shim.d.ts aswell.

πŸ” Where should you find it?
https://nuxt-typed-vuex.danielcroe.com/accessor/accessor.html#using-the-accessor

ℹ️ Additional context
TS: 3.75
Nuxt: 2.11.0

I use the vue composition api plugin aswell

docs: Improving state type with interface

Documentation link: https://nuxt-typed-vuex.danielcroe.com/store/state.html

Current example:

export const state = () => ({
  // AVOID: This results in emails being typed as never[]
  emails: [],

  // This is correct
  emails: [] as string[],
})

But we can make it even prettier with an interface:

interface IState {
  (): {
    emails: string[]
  }
}

export const state: IState = () => ({})

Or there is some issues with interface? I just used interfaces myself everywhere, instead of type casting with as syntax.

jest Unexpected token 'export'

πŸ› The bug
What isn't working? Describe what the bug is.
ts-jest is complaining about jest Unexpected token 'export' in the lib/index.js of the build package

Current lib/index.js:

export { getStoreType } from './types/store';
export { actionTree } from './types/actions';
export { getterTree } from './types/getters';
export { mutationTree } from './types/mutations';
export { useAccessor, getAccessorType, getAccessorFromStore } from './accessor';

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

🌈 Expected behaviour
What did you expect to happen? Is there a section in the docs about this?

using this package with a default vue/cli generated package, babel and ts-jest should work flawlessly

ℹ️ Additional context
Add any other context about the problem here.

You can workaround this, by changing your jest.config to something like:

...
transformIgnorePatterns: [
    '/node_modules/(?!typed-vuex)'
  ],
...

I'm not sure quite why it isn't able to interpretate the exports, maybe it's just my jest/babel settings. Feel free to close this as wont-fix, if this is caused specific by my settings, but at least its documented then. Also happy when you can point me to a possible solution or what the problem here is, I would be more then happy to provide a PR.

Thanks for the efforts on this package @danielroe , really solves some pains with vuex!

fix: Using this module breaks Vue Chrome Extension

πŸ› The bug
When using this module, the Vuex part of the official Vue Chrome Extension does not work properly. The mutations all show up fine, but the state is never updated, and you are unable to mutate state in the extension.

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

  1. Open the Vue extension
  2. Go to the Vuex tab
  3. Observe that the resulting state from the last mutation does not match what the last mutation committed.
  4. Try modifying the state using the extension – doesn't work (sometimes throws an error).

🌈 Expected behaviour
I would expect the Vue chrome extension to not be affected by this module.

ℹ️ Additional context
I'll try and get a sandbox going to demonstrate the issue, just don't have time right this minute.

fix: TSError2349 "This expression is not callable...." when calling action

πŸ› The bug
Typescript throws the following when calling an action This expression is not callable. Each member of the union type '(((options?: CommitOptions | undefined) => void) | ((payload: any, options?: CommitOptions | undefined) => void)) & (((options?: DispatchOptions | undefined) => void) | ((payload: any, options?: DispatchOptions | undefined) => void))' has signatures, but none of those signatures are compatible with each other.
However the function does work 🀷🏾 .

πŸ› οΈ To reproduce
I have a submodule subbyMcModuleface where doSomething is defined as an action per the docs:
E.g. in "store/subbyMcModuleface/actions.ts"

import { actionTree } from 'typed-vuex'
import initialState from './state'
import getters from './getters'
import mutations from './mutations'

export default actionTree(
  { state: initialState, getters, mutations },
  {
    doSomething({ commit }, data) {
      // do all the things
    },
  }
)

Then, in my component I to call store.subbyMcModuleface.doSomething() but doSomething is highlighted with the aforementioned error.

Have I missed something? I'll have to reluctantly use // @ts-ignore for that line as a workaround for now :(

🌈 Expected behaviour
TS doesn't complain, Vetur lint continues to bless my code πŸ™πŸΎ

ℹ️ Additional context

  • In case it's relevant, I'm using const store = useTypedStore() where useTypedStore is imported from const useTypedStore = wrapProperty('$accessor', false).
  • Also it's a Nuxt project (^2.15.2)

docs: Can't set the state properly with a mutation

πŸ“š Is your documentation request related to a problem? Please describe.

I've an store/account.ts module.
Here the relevant part to address my issue. (I'm using Helper functions)

export const state = () => ({
  isAuthenticated: false as boolean,
  user: {} as any,
)}
export const mutations = mutationTree(state, {
  setUser(state, newUser: any) {
    console.log('1', newUser)
    console.log('2', state.user)
    state.isAuthenticated = !!newUser
    state.user = newUser
},

and an action that commit setUser mutation

export const actions = actionTree(
  { state, getters, mutations },
  {
    async load({ commit, dispatch, getters, state }) {
      try {
        const user = await getAuthenticatedUser()
        this.app.$accessor.account.setUser(user)
      } catch (error) {
        this.app.$accessor.account.setUser(null)
      }
    },

If inspect the console.log('1', newUser) I have the expected object, but when I want to set in state with the mutation, the state is not updated correctly.

If I inspect the console.log('2', state.user) I see this:

{__ob__: Observer}
__ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
__proto__: Object

Can you clarify what's happening here?
I don't think this is an issue, but my mistake in the implementation phase

πŸ” Where should you find it?
https://typed-vuex.roe.dev/build
https://typed-vuex.roe.dev/mutations

ℹ️ Additional context
I provide the store/index.ts here:

import { GetterTree, MutationTree, ActionTree } from 'vuex'

import { getAccessorType } from 'typed-vuex'

import * as module1 from '~/store/module1'
import * as accountModule from '~/store/account'

export const state = () => ({})

export type RootState = ReturnType<typeof state>

export const getters: GetterTree<RootState, RootState> = {}

export const mutations: MutationTree<RootState> = {}

export const actions: ActionTree<RootState, RootState> = {
  nuxtServerInit ({ dispatch, commit }) {
    console.log(dispatch, commit)
  },
}

// TODO: improve types
export const accessorType: any = getAccessorType({
  state,
  getters,
  mutations,
  actions,
  modules: {
    module1,
    accountModule
  }
})

fix: Vuex Store is not updating in the Dev Tools

πŸ› The bug
Vuex store is never updated in the Vue/Vuex Dev Tools.
mutations, actions, getters all work. The pages are reactive, and work correctly.
However "Load state" in the Vue/Vuex devtools show the state as its initial state

πŸ› οΈ To reproduce
Go to the "Normal Usage" example
https://typed-vuex.roe.dev/build
Open the Web Browser section into a new window.
Open Vue Dev tools, go to the Vuex tab, and click "Load State"

🌈 Expected behaviour
I would expect the submodule firstName to be set to "John" after the 500ms timeout.
I would expect the email to be "[email protected]" after clicking the button.
However it only shows initial state

ℹ️ Additional context
I'm just getting started with Typescript in Vue/Vuex/Nuxt. I initially found this in my simple experimentation, however confirming this on the given example indicates its either an issue with my dev tools, the dev tools, or the package.

feat: Subscribe to store inside a component

Hi, thanks for this great plugin. I've been using it and pardon for not following the format.

Is there a way to subscribe to the store in a component? Something like this in options API:

  created() {
    this.$store.subscribe((mutation, state) => {
      if (mutation.type === 'snackbar/SHOW_MESSAGE') {
        this.message = state.snackbar.content;
        this.color = state.snackbar.color;
        this.show = true;
      }
    });
  }

I'm using vuetify currently and I had to create a plugin for a reusable snackbar since I cannot directly put a snackbar model in a store (mutation errors), so I had to subscribe to it and set the values locally.

Any help would be appreciated. Thanks.

docs: How to use 'this.$accessor' with Vue test utils, do you have un example ?

πŸ“š Is your documentation request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I feel I should be able to [...] but I can't see how to do it from the docs.

πŸ” Where should you find it?
What page of the docs do you expect this information to be found on?

ℹ️ Additional context
Add any other context or information.

docs: no info about nuxtServerInit()

There's no examples on how to use it with nuxtServerInit(), as i understood, we put it under ~/store/index.ts:

export const actions = actionTree(
  { state },
  {
    async nuxtServerInit({ dispatch }) {
      await dispatch('submodule/actionName')
    }
  }
)

But it doesn't fire my action from a submodule, also i'm getting a type error: Property 'dispatch' does not exist on type 'Pick<ActionContext<Required<NuxtStoreInput<() => { test: string; }, GetterTree<{ test: string; }, any>, MutationTree<{ test: string; }>, {}, {}>>>, "state" | "getters" | "commit" | "rootState" | "rootGetters">'.

feat: allow root mutations/actions from module store

πŸ› The bug
In vuex store there is a way to use root mutations/actions from module
https://vuex.vuejs.org/api/#commit

With nuxt-typed-vuex, as I understand, there is no such type in tree, so, when I pass this option and try to run my project, I get an error like

88:16 Argument of type '"rootMutation"' is not assignable to parameter of type '"actionDoSomething"'.

πŸ› οΈ To reproduce
Steps to reproduce the behavior:

  1. Add some mutations to root state
// index.ts
export const mutations = mutationTree(state, {
  rootMutation: (state: RootState) => {
    // mutate something
  },
});
  1. Try to use root mutation from module with { root: true } option like
// module.ts
export const actions = actionTree(
  { state, getters, mutations },
  {
    actionDoSomething({ commit }) {
      commit('rootMutation', null, { root: true });
    },
}
  1. Try to run the project
  2. Get an error in log

🌈 Expected behaviour
No errors

docs: A sample code may cause circular dependencies

πŸ“š Is your documentation request related to a problem? Please describe.
【Other action】 import 【accessor】, and ths 【accessor】 may import 【Other action】 too .
This will produce hidden annoying circular dependencies

πŸ” Where should you find it?
Getting started (Vue) - Typed Vuex

ℹ️ Additional context
A plugin to detect it : aackerman/circular-dependency-plugin: Detect circular dependencies in modules compiled with Webpack

docs: Please add submodule usage example.

Trying to expand on this example: https://codesandbox.io/s/github/danielroe/nuxt-typed-vuex-example?from-embed

I even made sure my local deps are exactly the same as those in the codesandbox.

While everything seems to work, this.$accessor.submodule seems to be undefined at runtime. And that's because submodule is a property of this.$accessor.modules, not of this.$accessor.

Therefore, all the typing available @ this.$accessor is kind of useless, since it is cast at the wrong level.

Could you please update the example above with one method and one action in the submodule and a usage example in any component?

Thank you very much.

Your efforts are wildly appreciated (unrelated to this particular, petty request). Stay safe.

docs: usage with Vue.component

πŸ“š Is your documentation request related to a problem? Please describe.
Docs explain how to get vuex types in class components (levaraging TS's decorators). I was wandering whether class components are mandatory or is also possible using typed-vuex with component instantiated via Vue.component.

πŸ” Where should you find it?
https://typed-vuex.roe.dev/getting-started-vue

ℹ️ Additional context
Thanks for the amazing job here. I'm considering introducing store types in a legacy project and I'm trying to figure out which supporting library would better fit our codebase.

fix: Deconstructing not existing object payload results in error.

πŸ› The bug

Deconstructing not existing object payload results in error.

TypeError: Cannot read property 'someProperty' of undefined

πŸ› οΈ To reproduce

export const actions = actionTree(
  {state, getters, mutations},
  {
    async someAction(
      {state, commit},
      {someProperty}: {someProperty?: string}
    ) {
       if (someProperty) // ... do something
    }
})

// in a component
this.$accessor.someAction() // results in error
this.$accessor.someAction({}) // works

🌈 Expected behaviour

There should ideally be no error if no object payload is given and the code is trying to deconstruct this not existing payload.


PS: Big thanks for the package. It's highly appreciated!

docs: dynamic modules (vuex modules stored in a different folder) asyncData not working

Hi Daniel, I have a nuxt.js project with typescript vuex and my CTO decided to have the root/modules folder in which to declare
the app modules.

So in this folder, I have a module called init-case which has a store inside. So we are talking here about dynamic modules, as described on your docs: /modules/init-case/store/initCase.ts

I am trying to call the asyncData from the .vue file inside these modules, but it seems that I cannot resolve this functionality.
I have recorded a loom for better details.

thank you.

https://www.loom.com/share/598336b4c5d948b39fe1ec07b3ca60df

fix: computed property re-evaluation doesn't work when used replaceState()

πŸ› The bug
Whenever store.state.count changes, it should cause the computed property with this.$accessor.count to re-evaluate.
But when used replaceState(), re-evaluation doesn't work.

πŸ› οΈ To reproduce
This is reproduction link:
https://codesandbox.io/s/17967

Steps to reproduce the behavior:

  1. Click increment/decrement, and it works.
  2. Reload on the browser on the sandbox.
  3. From the second time, replaceState() is used, and increment/decrement doesn't work.
  4. Comment out/Uncomment line 15/16 in index.vue, and it works.

🌈 Expected behaviour
When increment/decrement is clicked, it will cause the computed property to re-evaluate.

ℹ️ Additional context
I realized it when using with vuex-persistedstate.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.