So over the last lectures, we added or we created our store and we added actions,
now I also want to add my subscriptions. Subscriptions make sure that I don't have to manually call
getState here in my code if I want to get the current state snapshot but to inform me whenever I need to
get a new state because something changed, because if I manually do it like here in a console log,
I always have to guess if something changed.
So how do I create a subscription then? I access my store and there, I have a subscribe method I can execute.
Now subscribe takes an argument, a function which will be executed when ever the state is updated,
so whenever an action reached the reducer. The function we passed to subscribe doesn't get any arguments,
so here I'll use the ES6 arrow syntax with empty parentheses,
and then in the function body, we can execute any code we want on state updates.
So here, I'll log subscription,
just a marker so that I see where this is coming from
and now, I can also reach out to the store and get my state there. The getState method is the same as
before,
the difference is that I now know that I should get the state here because I know hey something changed
and that subscription
actually, of course typically is set up right after the store was created so that we get informed about
any future dispatches.
So I notice that subscribe comes before dispatching the actions and this function in the subscribe method
will be executed whenever action is dispatched and mutates the store.
With that, let's rerun this with node redux-basics.js and what we see is we first of all get the output
for the console log statement here after creating the store
and then, I get two subscription outputs and then the output here after the action is patching.
Now I get the two subscription outputs not because subscription comes before it getState, before
this console log statement but because it's triggered when ever an action is dispatched,
which of course happens before I do this console log statement.
This is how a subscription works,
it's getting triggered whenever the state is updated.
Now that's all nice and this is now showing us all the building blocks of redux,
however it doesn't show us at all how this fits into our react application.
So let's see how we connect redux to react
over the next lectures.