In the last lecture I talked about where to put your data transforming logic.
Now on the same page, if you chose the action creator, here's another utility method you might want to
know when working with thunk,
so with asynchronous code handled by redux-thunk, for example our storeResult here. We return a function
which gets dispatch handed into it as an argument by redux-thunk, which we can call to dispatch the action
once our async code is done, actually redux-thunk can pass as an additional argument, getState,
that is a method we can execute to get the current state.
Sometimes in your asynchronous code, you need to be able to reach out to the state prior to your to-be-
dispatched action,
let's say you want to save some data for a given user and you have the id of the user stored in your
redux state, you can then get it with getState,
for example here, we can get the old counter by executing getState here and simply accessing the counter
property, getState will give us the complete state which of course has a counter property or to be precise
since our reducers make up the state and we have two of them,
we can get the counter just as in the counter container in mapStateToProps, we have to access ctr.counter.
So we can do that
here, .ctr.counter in the action creator, thanks to the second argument passed into it by redux
thunk.
Now this old counter can then be output here,
old counter and I saw I have a typo there,
let's fix that.
So now if I save this and I store my result,
I actually get my old counter printed here on the right in the console, the blue 10 here.
That's the old counter I get right before dispatching this event which then actually leads to the code
executed in the reducer.
Now this is kind of related to what I said in the last lecture,
if you need it, it's a nice utility function,
don't overuse it though.
I try to write my action creators and reducers in a way that I don't have to use getState, instead
you can pass all the data you need in your async action creator like the user id into it by accepting
it as an argument.
That of course means that you need to have access to the data you need in your action creator in the
container where you actually dispatch the action leading to the action creator.
So here storeResult which leads to the async action creator,
here we would then have to pass this user ID or whatever it is and for that,
we of course need to have access to that user id in our container.
But that is something we might be able to expect and we should build our app accordingly.
If you just can't do that or don't want to, you have getState as a fallback and you can use it,
just don't over use it.
Don't put too much logic in there, at least is the route I take in my bigger react applications.