state
is a single reactive object that holds your whole application state. You can't modify the state directly.
const store = {
state: {
posts: [],
favoriteIds: []
}
}
State is modified by committing mutations
and the value is retrieved by using getters
.
const store = {
state: {
...
},
mutations: {
POSTS_SET (state, data) {
state.posts = data
},
FAVOURITE_ADD (state, id) {
state.favoriteIds.push(id)
},
FAVOURITE_REMOVE (state, idToRemove) {
state.favoriteIds = state.favoriteIds.filter(id => id !== idToRemove)
}
},
getters: {
posts (state) {
return state.posts
},
favoriteIds (state) {
return state.favoriteIds
}
}
}
modules
Modules allow cleaner store structure by giving you the option to organize specific logic in smaller chunks. Access modules with hooks by using their module name prefix, for example useGetter('project/projects')
or useMutation('project/PROJECTS_SET')
.
A module's structure is the same as the default store structure - it can contain state
, getters
, mutations
and actions
.
When working with getters, mutations and actions, the state
and the context
parameters are scoped to the current module. That means a module's getter can't see its parent state - and a module's action can't dispatch a parent's action, or commit a parent's mutation.
const store = {
state: {
...
},
mutations: {
...
},
getters: {
...
},
modules: {
project: {
state: {
data: [{ id: 1, title: 'Dummy project' }]
},
mutations: {
PROJECTS_SET (state, data) {
state.data = data
}
},
actions: {
async PROJECTS_FETCH (context) {
const data = await dummyApiCall()
context.mutations.PROJECTS_SET(data)
}
},
getters: {
projects (state) {
return state.data
}
}
}
}
}
withStore
withStore(Component: ReactNode, store: VuexStoreType) => (props: any) => JSX.Element;
Export your store
config file and use the withStore()
higher order component to wrap your root Component with it. withStore()
takes care of creating multiple contexts which will be used by the package-provided hooks.
Your implementation won't work if you don't wrap your root Component with the store config.
import React from 'react';
import ReactDOM from 'react-dom';
import { withStore } from 'vuex-but-for-react';
import App from './App';
import store from './store';
const AppWithStore = withStore(App, store);
ReactDOM.render(
<AppWithStore />,
document.getElementById('root')
);