React Lessons. Lesson 14.

react_14

Hey all! So, we continue working on our app. We already know how to make simple calls to the server and for 80% of possible cases this knowledge will be enough for executing standard tasks. However, we will learn how to deal with more complicated things, too. So, before moving on toward this task, I’d like to warn you that middleware  does not necessarily need to be written by yourself. It means these are such frequently used (re-used) elements that have already been written previously by someone else. We recommend you to explore this resource, where you will find a whole bunch of various middlewares and so on.  For example, here is a ready-to-use logger. We’ve created a logger to practice a little bit, but here is an example of a perfect ready-to-use solution.

Sometimes we want to do dispatch of several actions. For example, in  AC/articles.js deleteArticle we do dispatch of one action. But sometimes we need to repeat this command and apply it to several actions . In order not to write middleware  every single time we do this, we can simply return the type:'OTHER_ACTION" array:

And make them  dispatch followed by the other. For that reason we’ve got middleware redux-multi. But how does it work?
Just remember how we conducted the check – are we interested in some action or not? We did a check using a flag (as in middlewares/api.js), but there is another way for this action. For example, we know that reducers should get ‘flat’ objects. That’s why we can conduct a type-based check. If a type is not an object, but an array, we should divide them and dispatch them separately one after another. That’s what redux-multi does. If it receives an array with actions, it does dispatch of one followed by the other. You should understand that dividing in actions takes place inside  middleware, but you write them in one place for your convenience (in action creator). And, probably, the most popular middleware in Redux is redux-thunk. Just like redux-multi it checks everything it receives according to the type, and if it’s not an object, but a function, it calls this function inside itself and the dispatch takes place. Using it you can do asynchronous actions(in fact, sort of asynchronous). For example, the article upload could be described in a different way.

Let us install redux-thunk:

npm i redux-thunk --S

Go to AC/articles.js and add:

We return a function that will have an access to dispatch. Here we’ve partly copied logics from middlewares/api.js in order not to write it twice, but previously changing it a little. We will do the same action as previously, but in a different way.

Also change import in this file:

Do not forget to connect this middleware to store. To do so, move to  store/index.js  and add:

And place it somewhere in the very beginning for all our middlewares are waiting for some object, and if they receive a function instead of an object, we may have errors.

By placing redux-thunk at the first place we will have it checking whether a function is being received. If it is a function, it will work with it, otherwise it will delegate control to other middlewares. Now let us make sure we’ve got everything working, but first let us open containers/Articles.js and change one of import this way:

And right here, in this file inside export defaults , let us change the function that we call on the loadAllArticlesAlt:

So, let us check now, everything should be working! Look, we write asynchronous  actions (have a look at our code in AC/articles.js) right in action creator, although the code we’ve written is in fact being executed within middlewares. Here you can write rather complex logics, as well as you’ve got an access to the store state:

Thus, you can add something from store to execute the needed logics.

We’ve connected redux-thunk together with other middlewares in store; it checks the action type it has received. Whenever you write a middleware, you usually need to check out what kind of action you’ve received, whether it is interested in this middleware or you need to deliver control further. We’ve already done a flag-based check – for example, as it is standard for middlewares/randomId.js – and redux-thunk executes a type-based check. If it receives a function, it calls this function just like this:action(next, store.getState()). (action is our function here). And this action (this function) has already been described by us in Action Creator, inside  AC/articles.js, to be exactly – in loadAllArticlesAlt(). So, redux-thunk calls it by delivering the store state as an argument, as well as a capability to dispatch  your action further. And we use it, we take it and do dispatch applied to LOAD_ALL_ARTICLES + START in AC/articles.js:

Next we do asynchronous calls to API, wait for what will happen and do one more dispatch to LOAD_ALL_ARTICLES + SUCCESS or FAIL . We right this logics piece right inside the Action creator. Since we’ve got an access to the store state here, as well as an opportunity to do dispatch of several actions in a row, they may be asynchronous – that’s what we generally need in middlewares .

So, redux-thunk frees us from writing extra middlewares. If we need to execute some complicated logics that won’t be re-used (it means, it will be used only in one place), you can simply wrap it into a function by adding it to the Action Creator and further use redux-thunk.

If you need to execute a postponed call, you do it inside middleware, too. You won’t find this option in the Action creator  – it is just a pure function that returns an object. Moreover, we cannot do return through setTimeout. That’s why you will need to do something like this in your Action Creator AC/articles.js :

But why is redux-thunk not that perfect? Many developers completely forget about middlewares. Our tip is to make you remember that calls to the server are made within middlewares. You do not need to write all the logics inside action creators  using  redux-thunk. Or you just need to understand why you do all this stuff. You need to remember that actions should always be pure function, so avoid writing such things as a random id generation in there. Such solutions won’t let you make your app one of those with server rendering. The  middlewares are a perfect solution for being a centralized place for all  Side Effects. It means, whenever you want to transfer the business logics to a server or React-native, you will theoretically have a chance to use a number of things from the current logics, while only the middleware itself may be changed.

Your Home Task is to do the uploading of comments in a certain way that the comments are to be uploaded from the server upon a show comments click. Thus, the comments uploading will be executed from the address (for example), where the article’s id is contained at the very end:

http://localhost:8080/api/comment?article=56c782f18990ecf954f6e027

The lesson code can downloaded from here.

keep-calm14

We are looking forward to meeting you on our website soshace.com

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

React Lessons. Lesson 13 Part 2.

"Dear readers! Do not forget about the first part of this article, beginners should start from Lesson 1." So, let us call these elements inside ...

React Lesson 13. Part 1: Asynchronous actions

Our topic for today deals with asynchronous actions. We will start to take our articles from API. As you have already noticed, we have a simple API ...

React Lesson 12: Checking Homework Progress from Lesson 11

Hey everyone, In this lesson, we will go through our home task and learn how it is effective to connect the store to any component. Our home task was ...

No comments yet

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy