How to subscribe() to a combineReducer on Redux? - react-native

I`m using Redux on react-native with redux and react-redux. I use combinereducers() to combine two reducers:
const reducers = combineReducers({
sessiontype,
userdata
})
Now I subscribe to some change in my reducers:
store.subscribe((state, previousState) => {
//Do something
});
How I subscribe only to my userdata reducer? Because when I change the state of my sessiontype reducer I need to change the state of my userdata reducer (and It create a infinite cycle in my store.subscribe() because detect the whole reducer has modified.... (sorry my bad english)

The concept around Redux is that you have only one state and one reducer. The idea that you have separate reducers is just an implementation detail introduced by combineReducers() - it allows you to think of your reducers in parts, but to your application there's simply one reducer. Check out the discussion on this GitHub thread.
The mapStateToProps function inside the react-redux package allows you to select what parts of a reducer a component has access to. This may help you solve your issue. When a component with access to sessiontype updates the reducer, you can have that same component update userdata. To do that, you simply dispatch two separate actions to the store. Also, remember that subscribe does not actually give you access to the store - it simply let's you know that something has changed. Inside your subscribe function, you need to call getState() to actually read the data. Read more here.
Try something like this:
store.subscribe((state, prevState) => {
// run a check of conditions for an action being dispatched
// if you don't specify conditions, you'll end up in an
// infinite loop
if (stateHasFieldOrValue) {
// dispatch update to sessiontype
store.dispatch(updateSessionType(payload));
// dispatch update to userdata
store.dispatch(updateUserData(payload));
}
});

Related

Compare values before and after updating redux state

I am listening to a Firebase node.....then when a change occurs in FBS Im comparing the snapshot versus what's currently in Redux. Crazy thing is that Redux state already reflects the updated value in FBS (from snapshot) even before I've dispatched
const listenToFbsMyUserNode = (dispatch) => {
database()
.ref('profiles/users/')
.on('value', snapshot => {
let state = store.getState(); //at this point Redux somehow already knows about the updated value before Ive dispatched!!!
//now can dispatch
dispatch(_refreshMyProfile(snapshot.val()));
});
};
That means that you are probably copying Firebase objects into your store.
Since Firebase does not work immutably, Firebase does modify these objects - essentially also modifying your store with a dispatch, since your store now contains references to exactly these objects. Something like that should of course not happen - convert your objects into flat data before dispatching them instead of dispatching the Firebase objects directly.

Reflux setState with a Callback

EDIT AGAIN: Opened an issue with Reflux here: https://github.com/reflux/refluxjs/issues/544
EDIT: Reflux setState does not provide any callback for setState. They require you to use the component lifecycle methods to ensure the state is set prior to running any code. If you ever need to use the reflux setState outside of a component, where you do not have lifecycle methods, you will not be guaranteed the state is set. This is due to how Reflux does their setState. It loops all listening components and calls those components' setState methods. If Reflux were refactored to wait until all the listening components' setState calls complete then call a callback passed into its own setState method, that may work, but it would likely require a large rework of Reflux. I have started using a singleton class to manage some of these variables, as they are fully outside the component lifecycle.
Can you use setState with a callback in ReactNative or is that only in React? I'm using the below syntax and the first debugger is hit, but the second debugger and console log never get hit.
EDIT: After digging some more, it seems this does not occur when using setting the state directly, but only when running it through a reflux store and/or not using a component.
See snack here: https://snack.expo.io/S1dm3eFoM
debugger
this.setState(
params,
() => {
debugger
console.log("CALLIN IT BACK")
}
)
I'm the creator of Reflux's ES6 styled stores/component hookups. Hopefully I can shed some light on this for you.
Here's the important points:
1) Reflux sets its store state immediately upon setState calls.
Reflux's store state doesn't have the same problems as React and doesn't need React's workaround (callback). You are guaranteed that your change is immediately reflected in the store's state, that's why there is not a callback. The very next line of code will reflect the store's new state.
tl;dr, no workaround is required.
// in Reflux stores this works
this.setState({foo:'foo'});
console.log(this.state.foo === 'foo') // true
this.setState({foo:'bar'});
console.log(this.state.foo === 'bar') // true
2) Stores can never depend upon components!
The idea that the setState would give a callback about when the dependent components have all updated their state is a major violation of the single most fundamental of all flux principles: 1 way data flow.
If your store requires knowledge about whether or not components are doing something then you are already doing it wrong, and all the problems you are experiencing are XY problems of fundamentally not following flux in the first place. 1-way data flow is a main flux principle.
And that principle exists for good reason. Flux doesn't require 1:1 mapping of store state properties to component state properties. You can map anything to anything, or even just use the store's state for the building blocks of how you will run your own logic to create completely new state properties on the components. For example having loaded and transitioned as separate properties in store state, but mapping to a loadedAndTransitioned property in one component, and a notLoadedOrTransitioned in another component via your own custom logic. That's a hugely powerful part of flux. But your suggestion would pretty much destroy all that, since Reflux can't map people's custom logic.
1-way data flow must be maintained; Store's must operate the same independently of what components utilize them. Without this, the power of flux falls apart!
Store's listen to actions, components listen to stores, actions are called from wherever. All flux-based data flows from action -> store -> component only.
I've checked the library for the refluxjs and the problem and the workaround are as mentioned below.
Problem
The library provides with a new instance of the setState which is not exactly similar to ReactJS setState, which omits the callback as mentioned in their code below.
/dist/reflux.js
proto.setState = function (obj) {
// Object.assign(this.state, obj); // later turn this to Object.assign and remove loop once support is good enough
for (var key in obj) {
this.state[key] = obj[key];
}
// if there's an id (i.e. it's being tracked by the global state) then make sure to update the global state
if (this.id) {
Reflux.GlobalState[this.id] = this.state;
}
// trigger, because any component it's attached to is listening and will merge the store state into its own on a store trigger
this.trigger(obj);
};
Also as mentioned here in the docs
That store will store its state on a this.state property, and mutate its state via this.setState() in a way that is extremely similar to React classes themselves.
WorkAround
The library provides with the listener functions, which provide us with the callbacks of the setState obj of the ReactJS as mentioned in the below snippet.
/dist/reflux.js
componentDidMount: function() {
var me = this;
_.extend(me, ListenerMethods);
this.listenTo(listenable, function(v) {
me.setState(_.object([key],[v]));
});
},
You can use them in the following way
this.listenTo(action, callback)
Hope it clears the doubts
Edit:
Usage as per the docs
To listen inside of the store
constructor()
{
super();
this.state = {count: 0};
this.listenTo(increment, this.incrementItUp);
}
incrementItUp()
{
var newCount = this.state.count + 1;
this.setState({count: newCount});
}
To listen outside of the store anywhere
// listen directly to an action
myActions.actionName.listen(myCallbackFunc);
// listen to a child action
myActions.load.completed.listen(myCallbackFunc);
Here's the link to the snack with working callbacks based on Promises

How should I handle events in Vuex?

I am used to using a global event bus to handle cross-component methods. For example:
var bus = new Vue();
...
//Component A
bus.$emit('DoSomethingInComponentB');
...
//Component B
bus.$on('DoSomethingInComponentB', function(){ this.doSomething() })
However, I am building a larger project, which requires global state management. Naturally, I want to use Vuex.
While this bus pattern works with Vuex, it seems wrong. I have seen Vuex recommended as a replacement for this pattern.
Is there a way to run methods in components from Vuex? How should I approach this?
Vuex and event bus are two different things in the sense that vuex manages central state of your application while event bus is used to communicate between different components of your app.
You can execute vuex mutation or actions from a component and also raise events from vuex's actions.
As the docs says:
Actions are similar to mutations, the difference being that:
Instead of mutating the state, actions commit mutations.
Actions can contain arbitrary asynchronous operations.
So you can raise an event via bus from actions and you can call an action from any component method.
Using a global event bus is an anti pattern because it becomes very difficult to trace it (where was this event fired from? Where else are we listening to it? etc.)
Why do you want to use a global event bus? Is there some method that you want to trigger in another component? If you use Vuex then all your actions (methods) are in one central state and you can just dispatch your action.
So for example instead of doing this..
// Component A
bus.$emit('DoSomethingInComponentB');
// Component B
bus.$on('DoSomethingInComponentB', function(){ this.doSomething() })
With Vuex you would have the doSomething() function in a central store as an action. Then just make sure to convert you local component data to a global Vuex state data and dispatch that action.
this.$store.dispatch('doSomething')
It may not be directly what you are looking for, but I use watchers to respond to state changes. I come from an Angular background where having side effects respond to actions makes sense to me. To make this work I am having a particular value in the store change and then watch for the value in the relevant component like so:
Vue.component('comp-2', {
...
watch: {
mod1Foo() {
// do something here when the store value of the getter
// mod1/getFoo changes
}
},
computed: {
...mapGetters({
mod1Foo: 'mod1/getFoo'
})
}
});
Here is a full StackBlitz example: https://stackblitz.com/edit/js-gdme1g

Vuex Action vs Mutations

In Vuex, what is the logic of having both "actions" and "mutations?"
I understand the logic of components not being able to modify state (which seems smart), but having both actions and mutations seems like you are writing one function to trigger another function, to then alter state.
What is the difference between "actions" and "mutations," how do they work together, and moreso, I'm curious why the Vuex developers decided to do it this way?
Question 1: Why did the Vuejs developers decide to do it this way?
Answer:
When your application becomes large, and when there are multiple developers working on this project, you will find that "state management" (especially the "global state") becomes increasingly more complicated.
The Vuex way (just like Redux in react.js) offers a new mechanism to manage state, keep state, and "save and trackable" (that means every action which modifies state can be tracked by debug tool:vue-devtools)
Question 2: What's the difference between "action" and "mutation"?
Let's see the official explanation first:
Mutations:
Vuex mutations are essentially events: each mutation has a name and a
handler.
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
INCREMENT (state) {
// mutate state
state.count++
}
}
})
Actions: Actions are just functions that dispatch mutations.
// the simplest action
function increment ({commit}) {
commit('INCREMENT')
}
// a action with additional arguments
// with ES2015 argument destructuring
function incrementBy ({ dispatch }, amount) {
dispatch('INCREMENT', amount)
}
Here is my explanation of the above:
A mutation is the only way to modify state
The mutation doesn't care about business logic, it just cares about "state"
An action is business logic
The action can commit more than 1 mutation at a time, it just implements the business logic, it doesn't care about data changing (which is managed by mutation)
Mutations are synchronous, whereas actions can be asynchronous.
To put it in another way: you don't need actions if your operations are synchronous, otherwise implement them.
I believe that having an understanding of the motivations behind Mutations and Actions allows one to better judge when to use which and how. It also frees the programmer from the burden of uncertainty in situations where the "rules" become fuzzy. After reasoning a bit about their respective purposes, I came to the conclusion that although there may definitely be wrong ways to use Actions and Mutations, I don't think that there's a canonical approach.
Let's first try to understand why we even go through either Mutations or Actions.
Why go through the boilerplate in the first place? Why not change state directly in components?
Strictly speaking you could change the state directly from your components. The state is just a JavaScript object and there's nothing magical that will revert changes that you make to it.
// Yes, you can!
this.$store.state['products'].push(product)
However, by doing this you're scattering your state mutations all over the place. You lose the ability to simply just open a single module housing the state and at a glance see what kind of operations can be applied to it. Having centralized mutations solves this, albeit at the cost of some boilerplate.
// so we go from this
this.$store.state['products'].push(product)
// to this
this.$store.commit('addProduct', {product})
...
// and in store
addProduct(state, {product}){
state.products.push(product)
}
...
I think if you replace something short with boilerplate you'll want the boilerplate to also be small. I therefore presume that mutations are meant to be very thin wrappers around native operations on the state, with almost no business logic. In other words, mutations are meant to be mostly used like setters.
Now that you've centralized your mutations you have a better overview of your state changes and since your tooling (vue-devtools) is also aware of that location it makes debugging easier. It's also worth keeping in mind that many Vuex's plugins don't watch the state directly to track changes, they rather rely on mutations for that. "Out of bound" changes to the state are thus invisible to them.
So mutations, actions what's the difference anyway?
Actions, like mutations, also reside in the store's module and can receive the state object. Which implies that they could also mutate it directly. So what's the point of having both? If we reason that mutations have to be kept small and simple, it implies that we need an alternative means to house more elaborate business logic. Actions are the means to do this. And since as we have established earlier, vue-devtools and plugins are aware of changes through Mutations, to stay consistent we should keep using Mutations from our actions. Furthermore, since actions are meant to be all encompassing and that the logic they encapsulate may be asynchronous, it makes sense that Actions would also simply made asynchronous from the start.
It's often emphasized that actions can be asynchronous, whereas mutations are typically not. You may decide to see the distinction as an indication that mutations should be used for anything synchronous (and actions for anything asynchronous); however, you'd run into some difficulties if for instance you needed to commit more than one mutations (synchronously), or if you needed to work with a Getter from your mutations, as mutation functions receive neither Getters nor Mutations as arguments...
...which leads to an interesting question.
Why don't Mutations receive Getters?
I haven't found a satisfactory answer to this question, yet. I have seen some explanation by the core team that I found moot at best. If I summarize their usage, Getters are meant to be computed (and often cached) extensions to the state. In other words, they're basically still the state, albeit that requires some upfront computation and they're normally read-only. That's at least how they're encouraged to be used.
Thus, preventing Mutations from directly accessing Getters means that one of three things is now necessary, if we need to access from the former some functionality offered by the latter: (1) either the state computations provided by the Getter is duplicated somewhere that is accessible to the Mutation (bad smell), or (2) the computed value (or the relevant Getter itself) is passed down as an explicit argument to the Mutation (funky), or (3) the Getter's logic itself is duplicated directly within the Mutation, without the added benefit of caching as provided by the Getter (stench).
The following is an example of (2), which in most scenarios that I have encountered seems the "least bad" option.
state:{
shoppingCart: {
products: []
}
},
getters:{
hasProduct(state){
return function(product) { ... }
}
}
actions: {
addProduct({state, getters, commit, dispatch}, {product}){
// all kinds of business logic goes here
// then pull out some computed state
const hasProduct = getters.hasProduct(product)
// and pass it to the mutation
commit('addProduct', {product, hasProduct})
}
}
mutations: {
addProduct(state, {product, hasProduct}){
if (hasProduct){
// mutate the state one way
} else {
// mutate the state another way
}
}
}
To me, the above seems not only a bit convoluted, but also somewhat "leaky", since some of the code present in the Action is clearly oozing from the Mutation's internal logic.
In my opinion, this is an indication of a compromise. I believe that allowing Mutations to automatically receive Getters presents some challenges. It can be either to the design of Vuex itself, or the tooling (vue-devtools et al), or to maintain some backward compatibility, or some combination of all the stated possibilities.
What I don't believe is that passing Getters to your Mutations yourself is necessarily a sign that you're doing something wrong. I see it as simply "patching" one of the framework's shortcomings.
The main differences between Actions and Mutations:
In mutations you can change the state but not it actions.
Inside actions you can run asynchronous code but not in mutations.
Inside actions you can access getters, state, mutations (committing them), actions (dispatching them) etc in mutations you can access only the state.
I think the TLDR answer is that Mutations are meant to be synchronous/transactional. So if you need to run an Ajax call, or do any other asynchronous code, you need to do that in an Action, and then commit a mutation after, to set the new state.
I have been using Vuex professionally for about 3 years, and here is what I think I have figured out about the essential differences between actions and mutations, how you can benefit from using them well together, and how you can make your life harder if you don't use it well.
The main goal of Vuex is to offer a new pattern to control the behaviour of your application: Reactivity. The idea is to offload the orchestration of the state of your application to a specialized object: a store. It conveniently supplies methods to connect your components directly to your store data to be used at their own convenience. This allows your components to focus on their job: defining a template, style, and basic component behaviour to present to your user. Meanwhile, the store handles the heavy data load.
That is not the only advantage of this pattern though. The fact that stores are a single source of data for the entirety of your application offers a great potential for re-usability of this data across many components. This isn't the first pattern that attempts to address this issue of cross-component communication, but where it shines is that it forces you to implement a very safe behaviour in your application by basically forbidding your components to modify the state of this shared data, and force it instead to use "public endpoints" to ask for change.
The basic idea is this:
The store has an internal state, which should never be directly accessed by components (mapState is effectively banned)
The store has mutations, which are synchronous modifications to the internal state. A mutation's only job is to modify the state. They should only be called from an action. They should be named to describe things that happened to the state (ORDER_CANCELED, ORDER_CREATED). Keep them short and sweet. You can step through them by using the Vue Devtools browser extension (it's great for debugging too!)
The store also has actions, which should be async or return a promise. They are the actions that your components will call when they want to modify the state of the application. They should be named with business oriented actions (verbs, i.e. cancelOrder, createOrder). This is where you validate and send your requests. Each action may call different commits at different steps if it is required to change the state.
Finally, the store has getters, which are what you use to expose your state to your components. Expect them to be heavily used across many components as your application expands. Vuex caches getters heavily to avoid useless computation cycles (as long as you don't add parameters to your getter - try not to use parameters) so don't hesitate to use them extensively. Just make sure you give names that describe as closely as possible what state the application currently is in.
That being said, the magic begins when we start designing our application in this manner. For example:
We have a component that offers a list of orders to the user with the possibility to delete those orders
The component has mapped a store getter (deletableOrders), which is an array of objects with ids
The component has a button on each row of orders, and its click is mapped to a store action (deleteOrder) which passes the order object to it (which, we will remember, comes from the store's list itself)
The store deleteOrder action does the following:
it validates the deletion
it stores the order to delete temporarily
it commits the ORDER_DELETED mutation with the order
it sends the API call to actually delete the order (yes, AFTER modifying the state!)
it waits for the call to end (the state is already updated) and on failure, we call the ORDER_DELETE_FAILED mutation with the order we kept earlier.
The ORDER_DELETED mutation will simply remove the given order from the list of deletable orders (which will update the getter)
The ORDER_DELETE_FAILED mutation simply puts it back, and modifies the state to notify of the error (another component, error-notification, would be tracking that state to know when to display itself)
In the end, we have a user experience that is deemed as "reactive". From the perspective of our user, the item has been deleted immediately. Most of the time, we expect our endpoints to just work, so this is perfect. When it fails, we still have some control over how our application will react, because we have successfully separated the concern of the state of our front-end application, with the actual data.
You don't always need a store, mind you. If you find that you are writing stores that look like this:
export default {
state: {
orders: []
},
mutations: {
ADD_ORDER (state, order) {
state.orders.push(order)
},
DELETE_ORDER (state, orderToDelete) {
state.orders = state.orders.filter(order => order.id !== orderToDelete.id)
}
},
actions: {
addOrder ({commit}, order) {
commit('ADD_ORDER', order)
},
deleteOrder ({commit}, order) {
commit('DELETE_ORDER', order)
}
},
getters: {
orders: state => state.orders
}
}
To me it seems you are only using the store as a data store, and are perhaps missing out on the reactivity aspect of it, by not letting it also take control of variables that your application reacts to. Basically, you can and should probably offload some lines of code written in your components to your stores.
According to the docs
Actions are similar to mutations, the differences being that:
Instead of mutating the state, actions commit mutations.
Actions can contain arbitrary asynchronous operations.
Consider the following snippet.
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++ //Mutating the state. Must be synchronous
}
},
actions: {
increment (context) {
context.commit('increment') //Committing the mutations. Can be asynchronous.
}
}
})
Action handlers(increment) receive a context object which exposes the same set of
methods/properties on the store instance, so you can call
context.commit to commit a mutation, or access the state and getters
via context.state and context.getters
Mutations:
Can update the state. (Having the Authorization to change the state).
Actions:
Actions are used to tell "which mutation should be triggered"
In Redux Way
Mutations are Reducers
Actions are Actions
Why Both ??
When the application growing , coding and lines will be increasing , That time you have to handle the logic in Actions not in the mutations because mutations are the only authority to change the state, it should be clean as possible.
Disclaimer - I've only just started using vuejs so this is just me extrapolating the design intent.
Time machine debugging uses snapshots of the state, and shows a timeline of actions and mutations. In theory we could have had just actions alongside a recording of state setters and getters to synchronously describe mutation. But then:
We would have impure inputs (async results) which caused the setters and getters. This would be hard to follow logically and different async setters and getters may surprisingly interact. That can still happen with mutations transactions but then we can say the transaction needs to be improved as opposed to it being a race condition in the actions. Anonymous mutations inside an action could more easily resurface these kinds of bugs because async programming is fragile and difficult.
The transaction log would be hard to read because there would be no name for the state changes. It would be much more code-like and less English, missing the logical groupings of mutations.
It might be trickier and less performant to instrument recording any mutation on a data object, as opposed to now where there are synchronously defined diff points - before and after mutation function call. I'm not sure how big of a problem that is.
Compare the following transaction log with named mutations.
Action: FetchNewsStories
Mutation: SetFetchingNewsStories
Action: FetchNewsStories [continuation]
Mutation: DoneFetchingNewsStories([...])
With a transaction log that has no named mutations:
Action: FetchNewsStories
Mutation: state.isFetching = true;
Action: FetchNewsStories [continuation]
Mutation: state.isFetching = false;
Mutation: state.listOfStories = [...]
I hope you can extrapolate from that example the potential added complexity in async and anonymous mutation inside actions.
https://vuex.vuejs.org/en/mutations.html
Now imagine we are debugging the app and looking at the devtool's mutation logs. For every mutation logged, the devtool will need to capture a "before" and "after" snapshots of the state. However, the asynchronous callback inside the example mutation above makes that impossible: the callback is not called yet when the mutation is committed, and there's no way for the devtool to know when the callback will actually be called - any state mutation performed in the callback is essentially un-trackable!
This confused me too so I made a simple demo.
component.vue
<template>
<div id="app">
<h6>Logging with Action vs Mutation</h6>
<p>{{count}}</p>
<p>
<button #click="mutateCountWithAsyncDelay()">Mutate Count directly with delay</button>
</p>
<p>
<button #click="updateCountViaAsyncAction()">Update Count via action, but with delay</button>
</p>
<p>Note that when the mutation handles the asynchronous action, the "log" in console is broken.</p>
<p>When mutations are separated to only update data while the action handles the asynchronous business
logic, the log works the log works</p>
</div>
</template>
<script>
export default {
name: 'app',
methods: {
//WRONG
mutateCountWithAsyncDelay(){
this.$store.commit('mutateCountWithAsyncDelay');
},
//RIGHT
updateCountViaAsyncAction(){
this.$store.dispatch('updateCountAsync')
}
},
computed: {
count: function(){
return this.$store.state.count;
},
}
}
</script>
store.js
import 'es6-promise/auto'
import Vuex from 'vuex'
import Vue from 'vue';
Vue.use(Vuex);
const myStore = new Vuex.Store({
state: {
count: 0,
},
mutations: {
//The WRONG way
mutateCountWithAsyncDelay (state) {
var log1;
var log2;
//Capture Before Value
log1 = state.count;
//Simulate delay from a fetch or something
setTimeout(() => {
state.count++
}, 1000);
//Capture After Value
log2 = state.count;
//Async in mutation screws up the log
console.log(`Starting Count: ${log1}`); //NRHG
console.log(`Ending Count: ${log2}`); //NRHG
},
//The RIGHT way
mutateCount (state) {
var log1;
var log2;
//Capture Before Value
log1 = state.count;
//Mutation does nothing but update data
state.count++;
//Capture After Value
log2 = state.count;
//Changes logged correctly
console.log(`Starting Count: ${log1}`); //NRHG
console.log(`Ending Count: ${log2}`); //NRHG
}
},
actions: {
//This action performs its async work then commits the RIGHT mutation
updateCountAsync(context){
setTimeout(() => {
context.commit('mutateCount');
}, 1000);
}
},
});
export default myStore;
After researching this, the conclusion I came to is that mutations are a convention focused only on changing data to better separate concerns and improve logging before and after the updated data. Whereas actions are a layer of abstraction that handles the higher level logic and then calls the mutations appropriately
Because there’s no state without mutations! When commited — a piece of logic, that changes the state in a foreseeable manner, is executed. Mutations are the only way to set or change the state (so there’s no direct changes!), and furthermore — they must be synchronous. This solution drives a very important functionality: mutations are logging into devtools. And that provides you with a great readability and predictability!
One more thing — actions. As it’s been said — actions commit mutations. So they do not change the store, and there’s no need for these to be synchronous. But, they can manage an extra piece of asynchronous logic!
It might seem unnecessary to have an extra layer of actions just to call the mutations, for example:
const actions = {
logout: ({ commit }) => {
commit("setToken", null);
}
};
const mutations = {
setToken: (state, token) => {
state.token = token;
}
};
So if calling actions calls logout, why not call the mutation itself?
The entire idea of an action is to call multiple mutations from inside one action or make an Ajax request or any kind of asynchronous logic you can imagine.
We might eventually have actions that make multiple network requests and eventually call many different mutations.
So we try to stuff as much complexity from our Vuex.Store() as possible in our actions and this leaves our mutations, state and getters cleaner and straightforward and falls in line with the kind of modularity that makes libraries like Vue and React popular.
1.From docs:
Actions are similar to mutations, the differences being that:
Instead of mutating the state, actions commit mutations.
Actions can contain arbitrary asynchronous operations.
The Actions can contain asynchronous operations, but the mutation can not.
2.We invoke the mutation, we can change the state directly. and we also can in the action to change states by like this:
actions: {
increment (store) {
// do whatever ... then change the state
store.commit('MUTATION_NAME')
}
}
the Actions is designed for handle more other things, we can do many things in there(we can use asynchronous operations) then change state by dispatch mutation there.

Subscribe to single property change in store in Redux

In Redux I can easily subscribe to store changes with
store.subscribe(() => my handler goes here)
But what if my store is full of different objects and in a particular place in my app I want to subscribe to changes made only in a specific object in the store?
There is no way to subscribe to part of the store when using subscribe directly, but as the creator of Redux says himself - don't use subscribe directly! For the data flow of a Redux app to really work, you will want one component that wraps your entire app. This component will subscribe to your store. The rest of your components will be children to this wrapper component and will only get the parts of the state that they need.
If you are using Redux with React then there is good news - the official react-redux package takes care of this for you! It provides that wrapper component, called a <Provider />. You will then have at least one "smart component" that listens to state changes passed down by the Provider from the store. You can specify which parts of the state it should listen to, and those pieces of the state will be passed down as props to that component (and then of course, it can pass those down to its own children). You can specify that by using the connect() function on your "smart" component and using the mapStateToPropsfunction as a first parameter. To recap:
Wrap root component with Provider component that subscribes to store changes
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
Now any child of <App /> that is wrapped with connect() will be a "smart" component. You can pass in mapStateToProps to pick certain parts of the state and give it those as props.
const mapStateToProps = (state) => {
return {
somethingFromStore: state.somethingFromStore
}
}
class ChildOfApp extends Component {
render() {
return <div>{this.props.somethingFromStore}</div>
}
}
//wrap App in connect and pass in mapStateToProps
export default connect(mapStateToProps)(ChildOfApp)
Obviously <App /> can have many children and you can pick and choose which parts of the state the mapStateToProps should listen to for each of its children. I'd suggest reading the docs on usage with React to get a better understanding of this flow.
Redux only offers a single generic way to know when the store has updated: the subscribe method. Callbacks to subscribe do not get any info on what might have changed, as the subscribe API is deliberately low-level, and simply runs each callback with no arguments. All you know is that the store has updated in some way.
Because of that, someone has to write specific logic to compare old state vs new state, and see if anything has changed. You could handle this by using React-Redux, specifying a mapStateToProps function for your component, implementing componentWillReceiveProps in your component, and checking to see if specific props from the store have changed.
There are also a couple addon libraries that try to handle this case: https://github.com/ashaffer/redux-subscribe and https://github.com/jprichardson/redux-watch . Both basically let you specify a specific portion of the state to look at, using different approaches.
In addition to what Andy Noelker said, mapStateToProps not only passes part of the state properly down your component tree, it also subscribes to changes made directly in these subscribed portions of the state.
It is true that every mapStateToProp function you bind to the store gets called each time any part of the state is changed, but the result of the call gets shallow compared to the previous call - if top level keys you subscribed onto did not change (the reference stays the same). Then mapStateToProps would not call re-render. So if you want the concept to work, you have to keep mapStateToProps simple, no merging, type changing or anything, they should simply pass down parts of the state.
If you want to reduce the data from the state when subscribing, for example you had list data in the state and you want to convert it to object with ids as keys, or you want to join multiple states into data structures, you should combine mapStateToProps with createSelector from reselect library, by doing all these modifications inside selector. Selectors are pure functions that reduce and cache state chunks passed in as input and if input did not change - they return exactly the same reference they did on the last call - without performing the reduction.
Created a hack to help understand the subscribers can be differentiated based on store data, with multiple store capability.
//import { createStore } from 'redux';
let createStore = require('redux').createStore;
let combineReducers = require('redux').combineReducers;
/**
* This is a reducer, a pure function with (state, action) => state signature.
* It describes how an action transforms the state into the next state.
*
* The shape of the state is up to you: it can be a primitive, an array, an object,
* or even an Immutable.js data structure. The only important part is that you should
* not mutate the state object, but return a new object if the state changes.
*
* In this example, we use a `switch` statement and strings, but you can use a helper that
* follows a different convention (such as function maps) if it makes sense for your
* project.
*/
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
function messanger(state = 'Mr, khazi', action) {
switch(action.type) {
case 'WELCOME':
return 'Hello, Mr Khazi';
case 'BYE':
return 'Bye, Mr Khazi';
case 'INCREMENT':
return 'Incremented khazi';
default:
return state;
}
};
function latestAction(state = null, action) {
switch(action.type) {
case 'WELCOME':
return '$messanger';
case 'BYE':
return '$messanger';
case 'INCREMENT':
return '$messanger, $counter';
case 'DECREMENT':
return '$counter';
default:
return state;
}
};
let reducers = {
counts: counter,
message: messanger,
action: latestAction
};
let store = createStore(
combineReducers(reducers, latestAction)
);
// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
//let store = createStore(counter)
// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.
store.subscribe(() => {
if(store.getState().action.indexOf('messanger') !== -1) {
console.log('subscribed for counter actions', store.getState());
}
});
store.subscribe(() => {
if (store.getState().action.indexOf('counter') !== -1) {
console.log('subscribed for messanger actions', store.getState());
}
});
// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
console.log('----------------Action with both subscriber-------------');
store.dispatch({ type: 'INCREMENT' });
console.log('---------------Action with counter subscriber-----------');
store.dispatch({ type: 'DECREMENT' });
console.log('---------------Action with messenger subscriber---------');
store.dispatch({ type: 'WELCOME' });
/*
every reducer will execute on each action.
*/