danielroe/typed-vuex

Issues when accessing the state from within an action

Pitu opened this issue ยท 4 comments

Pitu commented

๐Ÿ› The bug
I can't access the correct state from an action.

๐ŸŒˆ Expected behaviour
When dispatching an action I should be able to read the contents of the state, yet state.coins is undefined here when it should be an empty array.

โ„น๏ธ Additional context

import { actionTree, getAccessorType } from 'typed-vuex';

interface Coin {
	id: number;
}

interface State {
	coins: Coin[];
}

export const state = (): State => ({
	coins: []
});

export type RootState = ReturnType<typeof state>;

export const actions = actionTree({ state },
	{
		async get({ state }) {
			console.log(state) // state.coins = undefined
		}
	});

export const accessorType = getAccessorType({
	state,
	actions
});

This is the console.log output
image

@Pitu Would you provide a reproduction on CodeSandbox?

Here's a working example: https://codesandbox.io/s/angry-mirzakhani-hk827?file=/store/index.js

Pitu commented

Sure thing, I'll try to get a repo up and running today for you to check it out.
Thanks a lot!

Pitu commented

By recreating my code using your link I found out what the problem was.
The snippet I pasted up there had a few lines removed that I thought were inconsequential to the problem but they were indeed what was causing the problem. I was trying to commit to state.coins a value that didn't exist and thus it was undefined.

Sorry for the inconvenience!

@Pitu No problem - glad everything was resolved!