In this article, we will compare the syntax for the most famous state management library in both ecosystems — Redux & Vuex.
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'
const store = createStore(todoApp)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
const store = new Vuex.Store({
state: { ... },
mutations: { ... }
})
...
new Vue({
el: '#app',
store,
});
const ADD_TODO = 'ADD_TODO'
function addTodo(text) {
return {
type: ADD_TODO,
text,
}
}
const store = new Vuex.Store({
actions: {
increment (context) {
context.commit('increment') // commit a mutation to trigger state update
}
}
})
// apply redux-thunk
import thunkMiddleware from 'redux-thunk'
const store = createStore(
rootReducer,
applyMiddleware(thunkMiddleware)
)
...
export function fetchPosts() {
return function (dispatch) {
dispatch(requestPosts())
return fetch('xxx')
.then(response => response.json())
.then(json => dispatch(receivePosts(json)))
}
}
actions: {
async fetchPosts ({ commit }) {
commit('requestPosts');
const res = await fetch('xxx');
commit('receivePosts', res);
},
}
#vuex #reselect #react-redux #redux #react #programming