Using Redux Saga To Manage Your Side Effects

If you’re using Redux anytime by now, you’ll realize as your codebase goes large, so does your side effects. And by side effects I mean data fetching, or any async processes that needs special treatment.

Previously people would suggest to use redux-thunk, which basically is an action creator that returns a function, in which it will be invoked in your middleware. But it has it’s own challenges:

  • it’s not testable
  • no concurrency
  • the bigger the codebase, the more complicated it will be

Having Redux Saga as one of your dependency will tremendously makes life much easier as it abstracts complex async operation beneath the library’s core.

There are several prerequisite before proceeding to look for Redux Saga, you need to understand about generators and promises, better yet, async-await style.

This is because Redux Saga uses generators. Implementing a saga requires you to keep yielding stuff.

I suggest you to read the following beforehand:

Introduction

Redux Saga === Middleware

Yup, Redux Saga is just another kind of middleware that will intercept any of your dispatched action before handing it over to your reducer.

Getting Started

Because it’s a middleware, you need to specify your saga when creating your Redux store.

import {  
  createStore,
  applyMiddleware,
} from 'redux'
import createSagaMiddleware from 'redux-saga'  
import reducer from './reducers'  
import mySaga from './sagas'

// create the saga middleware
const sagaMiddleware = createSagaMiddleware()  
// mount it on the Store
const store = createStore( reducer, applyMiddleware(sagaMiddleware) )  
// then run the saga
sagaMiddleware.run(mySaga)  

This code is taken from the official documentation.

Watcher and Worker Saga

Generally you’ll have two kinds of saga:

  • Watcher Saga

  • Worker Saga

Watcher Saga watches for any incoming dispatched action.

When it receives one, it will spawns/initiate a worker saga, often referred to as a task, which will do the work.

I like to think a task as just another layer of middleware, but with a special ability of pausing and resuming.

Therefore, you can initiate multiple of worker saga/tasks at the same time, each will work concurrently.

Effects

You’ll see from the preceding code there’s a magic call  and put  invocation. call *and *put doesn’t directly invoke a function that does the work, instead it returns an instruction for the middleware to execute.

Here’s what it looks like:

{
  CALL: {
    fn: Api.fetch,
    args: ['./products']
  }
}

This kind of pattern is seen in a lot of libraries, including React’s React.createElement().

Redux Saga call this as an effect.

Call and put is two of several other effects Redux Saga introduces, but frankly you won’t need all.

Combining it all

Here’s what a typical watcher and worker saga would look like:

// defining your watcher saga
function* watcherSaga() {  
  yield takeLatest('FETCH_ALL_USERS_DATA', workerSaga);
}
// defining your worker saga
function* workerSaga(action) {  
  yield fetchResult = call(httpRequest);
  yield put({
    type: 'FETCH_RECEIVED',
    payload: fetchResult,
  });
}

Take a closer look on mySaga from the previous chunk of code, and that will be your saga’s starting point.

You’ll generally will always start with a watcher saga, it means that mySaga will be a watcher saga.

On this sagaMiddleware.run(mySaga) line of code, Redux Saga will directly runs your mySaga.

And what mySaga will generates is an instruction for the middleware!

So from the previous example, takeLatest will generate an instruction.

What does this instruction says?

It says to wait for the latest dispatched action FETCH_ALL_USERS_DATA, and when that action is dispatched, initiate the specified worker saga.

You can build your watcher saga like this:

function* watcherSaga() {  
  yield takeLatest('ACTION_A', workerSagaA);
  yield takeLatest('ACTION_B', workerSagaB);...and so on
}

Redux Saga flow on sagaMiddleware.run(watcherSaga) call:

  1. watcherSaga is called.

  2. watcherSaga will returns an instruction for ACTION_A.

  3. middleware receive the instruction then continues to run watcherSaga.

  4. watcherSaga returns another instruction for ACTION_B.

  5. middleware receives the instruction then continues to run watcherSaga.

This whole process will stop whenever a blocking effect is reached, commonly known blocking effects are:

  • call

  • take

Call returns an instruction to the middleware to call the given function (which has to return a promise). The middleware will wait until the promise resolves and then continue to run the saga.

Take returns an instruction to the middleware to wait for a specific action before proceeding the saga.

What I was just elaborating what happens when sagaMiddleware.run(watcherSaga) is called, which in essence, just to provide as many instruction to the middleware.

You can deep more in the official documentation here: http://yelouafi.github.io/redux-saga/

Or even try yourself the library which you can find here: https://github.com/yelouafi/redux-saga

JavaScript for Noobs: Prototype using Function Constructor

As of my last post about prototypal inheritance, this post will go even further about the actual usage of prototype. On that last post I’ve discuss about how we can use proto  (underscore-underscore-proto-underscore-underscore) to access/mutate a JavaScript object.

On this post on the other hand, I’d like to discuss on how we suppose to use a function constructor.

If you haven’t checked on that last post, I suggest you to do so. Here’s the link to the previous series of prototypal inheritance.

function constructor and prototype

(Picture from Udemy’s course JavaScript: The Weird Parts)

Function, as you know, can functioned as a constructor, that is a special block of code that is invoked when you’re trying to create a new object using the new  operator.

There are no supplementary between a constructor and a normal function, they are just the same.

Although a constructor has the ability to access the newly created object, the constructor will be invoked using a pseudo parameter consisting a hidden reference of that newly created object. Afterwards, the reference is kept inside the this  keyword.

If you’re not familiar with function acting as a constructor, let me explain it a bit. The common method of using a function constructor is:

var obj = new randomFunction(param1, param2);  

new  is an operator, and in JavaScript operators are function. The new  keyword takes a certain parameters new … ([ … , … ]) .

When the JavaScript engine reads the keyword, it will create an entirely new object, and invoked the function constructor you provide along with the reference of that new object.

As long as the function constructor doesn’t have it’s own return expression, the JavaScript engine will automatically return the new object reference upon the entire new  expression.

Now.

When a function act as a constructor, and a *new  expression works upon him, then the prototype property (object) will live. *

It’s funny how the prototype for the function actually not the prototype for the function, it’s the prototype for the object that is created using that function constructor.

Prototype is useful so that any object that is created with the same function, sometime later we can add features to all of those objects at once by using this .prototype  property of the function constructor.

function randomFunction(firstName, lastName) {  
    this.firstName = firstName;
    this.lastName = lastName;
}
var randomObj = new randomFunction("Elon", "Musk");  
randomFunction.property.middleName = "John";  

The this keyword on a prototype will refers to the caller object.

randomFunction.property.randomProp = this.firstName + " " + this.lastNameasdasdasdsadasdasdasdas  
console.log(randomObj.randomProp);  

It will output “Elon Musk”.

For efficiency, put all methods inside the prototype, properties sometimes have different value thus not included in the prototype. Here’s what I’m talking about:

randomFunction.property.randomFunction = function(val) { return val; } var output = randomObj.randomFunction("Hello!"); console.log(output); // outputs Hello!

JavaScript for Noobs: What the heck is __proto__?

Prototypal inheritance is one component that gets acquaintance in JavaScript. You probably familiar with the classic inheritance which is wildly use among other programming languages, for instance: Java and C++.

Well, although prototypal inheritance is slightly similar with classic inheritance, but in fact, it is so much simple. In my opinion, though classic inheritance provides a decent structure for the code, but even a non-programmers can clearly notice it’s verbosity.

The concept of prototypal inheritance is pretty much easy to digest. Tip: keep it simple, don’t overthink it. Every object (except for a base object, we’ll cover it later) in JavaScript have this so-called prototype object as their properties. It consist of built-in properties/methods.

Here’s the thing: if you try to access a properties/method of an object and JavaScript engine doesn’t finds one, then it will search through it’s prototype object.

A prototype object may links to another prototype object. The only object that doesn’t refers to another prototype is a base object, and that said, is the bottom of the prototype chain.

There are several methods you could you use to mutate the prototype object, let’s deliberate one scheme that is not recommended due to performance issue. The following method will only make your code slow! But we’ll cover it for demo purposes.

Using proto

You can access an object’s prototype through proto  (dash-dash-proto-dash-dash). Remember to never ever everrr use this method.

proto  is available to all objects: object literals, functions, and even arrays. Let’s examine each, shall we.

Object Literals

The following is the proto  result when for an object literals, I have declared variable *a * previously as an object literals: var a = {};

object literal prototype

As you can see the prototype of the variable a  is an object. In this case, it’s a base object, that means it’s the end the prototype chain, there won’t be any other prototype object inside of this prototype.

Function

Here’s the result when you try to access it’s prototype:

function prototype

Hmm, interestingly, it’s an empty function. I’m not really sure about the idea around this, but as you know, function is literally an object too, hence there won’t be much difference whether the result is an Object {}  or a function Empty() {} .

You might wanna see what actually lies inside the prototype object, in this case, the first prototype object of the any function.

function prototype 2

Are you surprised? You might want to glimpse on methods like apply() , bind(),  and call() . You probably have used those methods several times, and yet you can’t figure why they’ re available to all functions out there. Well now you know, it’s there accessible thanks to JavaScript engine which discreetly put it under the hood, for you.

Now, I’d like to show you the base object of function objects:

function prototype base object

There you go!

Another proto  prototype lies inside the first proto  property. And, it’s an object, so as you might guess, it’s a base object, end of the prototype chain.

Array

Similar to function, but differs in the first proto  object:

array object prototype

Note that I’ve declared variable c*  *right before the statement. It appears that the proto  of an array is an array object as well. But, likewise a function, arrays are objects. Let’s just treat them the same.

Take a look at the built-in method/properties of it’s prototype object:

array object built-in

Yeah, push() , pop() , reduce() , and all other fancy methods come into sight. It’s kinda astonishing to discover their hideout.

On the next post I’ll discuss how to put prototype into real play. Just bear in mind that the proto  we conferred foregone is intended for nothing but awareness.

So You Wanna Learn JavaScript? (Part 2)

As of my last post on So You Wanna Learn JavaScript, I promised to put on several websites which I believe is rudimentary to enhance your JavaScript problem solving and algorithm skill.

So, besides on intensifying your knowledge on the concept, you need to actively put it on practice. Therefore these websites are really useful in making it happen.

Lets get straight down to it.

Free Code Camp

It's actually not design specifically for this purpose, yet Free Code Camp (FCC) is one of the best free open source website you could find to practice your JavaScript skill.

FCC mapped out to produce skilled web developer with tons of projects (which probably kind of what differentiate it from other sort of camps).

free code camp javascript algorithm practice

It has up to 150 algorithm scripting practice (on average) for JavaScript itself!

Pretty nice, right :)

You won't find common algorithm pattern come into practice (binary search, divide and conquer, etc). It will pivot on your ability to solve problems.

Here's one of it's advance algorithm scripting problem:

free code camp algorithm problem

It's nice to see how they even provide some helpful links you can check on:

helpful link free code camp

The test case you probably wondering, they spring it up so you'd know where you did wrong.

free code camp test case

One nice thing about them, is the awesome smooth user interface. free code camp UI

CoderByte

Plenty suggest CoderByte too. They have an organized sections of challenges difficulty, ranges from easy to hard.

I saw on the other day where Hack Reactor, the coding Bootcamp which specialized in JavaScript, ask their prospective students to practice on this site before going on their technical interview. There is a private section for you to prepare specifically to several bootcamp admission, including Hack Reactor, App Academy, and Fullstack Academy. They also provide a job interview questions for top companies like Google or Microsoft. Too bad they put on charge for you to access it :(

One thing I hate is their lousy UI. Kind of buggy, so you probably want to check out an online editor such as repl.it, and set the language to JavaScript.

One quick preview of it:

coderbyte user interface

There are currently 36 easy challenges, 33 medium challenges, and 45 hard challenges. See if you can solve them all :)

They have point system determined by the accuracy of your code and the time you need to solve it.

Code Wars

One of the best and recommended by many due to it's "war" feel and touch. I'm pretty sure many of you will love Code Wars.

Many of their problems (known as kata) is made by the users, so it keeps growing and growing. In terms of difficulty, you can find it ranges from 1-8. They call it kyu. So, there will be questions mark with 1 kyu until 8 kyu. You will start of with 8 kyu rank, and will level up gradually as you finish the challenges.

One sample question of a 7 kyu kata:

sample problem of code wars

You can define your own test cases:

code wars user interface

One awesome thing about this website is that you can see solutions by other "warriors" and vote for which you consider the best practice and clever. You'd find new ways of solving the problems, techniques you wouldn't realize before, which is GREAT!

best practice code wars

That's all from me, let me know what you think by leaving a comment!

I'll try to come up with more websites for you to try. Cheers :)

So You Wanna Learn JavaScript?

Previously, I made a series of post named JavaScript for Noobs. Not because I'm sort of 'the Javascript guru', but more less of a documentation of my studies around the technology.

Javascript is a pretty mean language, isn't she?

It's an easy way through at the start, but as times go on, it's an undoubtedly nightmare. That is because Javascript has a "steep learning curve".

What I meant is this:

steep-learning-curve

As you can see, the amount of time required to enhance your skill right from the kickoff is genuinely steep, that is, with a little amount of time, you're able to posses lots of knowledge/skill.

BUT,

when your skill levels at a certain scale, the graph moves much more gently, which probably close to a parallel of the x-axis. This, is when things get ridiculously hard.

By the way, the graph aren't quite illustrating what I'm saying, so let's change it:

steep learning curve

Aha! Now this does a great job emphasising what I meant.

Anyway, why would someone in particular want to learn Javascript? Besides, there are dozens of other programming languages worth to learn too.

You should definitely watch the following video:

[su_youtube url="https://www.youtube.com/watch?v=Bx17ywo-5nM"]

Scott Hanselman, one of the top web developers I'm currently admire of, suggesting that if you know Javascript and an enterprise language (such as C# or  Java), you basically can create anything on any platform.

Javascript is EVERYWHERE!

One hell of a shortcut on learning Javascript is to team up with developer bootcamp. I'm particularly aiming for a bootcamp known as the Hack Reactor. I'm after the remote beta, since my geographic location is not particularly helpful.

Anyway, the key point of this post is to elaborate several resources in regards to learning Javascript.

For now, I would give you the resources to it's concept, tune up for next post in regards to practices!

Concept

I came across with several sources, I find these references helpful in terms of bringing up the basic concepts of Javascript nor the primary building blocks.

  • PluralSight

It's one of the best and complete reference yet, but in came with a price (monthly/annually subscription). But, if you really mean of learning Javascript, you can nail it for a month. Go check it's Javascript learning path. I must warn you that some of it's content are not beginners stuff, although it is labeled for beginners (or probably is just me).

  • Javascript Is Sexy

I'm sure you heard of it. In fact, it now has an official website for it's course, similar like a bootcamp. By the release of this post, Javascript is Sexy is going for their second cohort. That one thing I love about this website is their meticulous attention to detail. They are giving step by step guide on learning Javascript properly, so you won't messed up, or jumping randomly and miss some fundamentals.

  • Eloquent Javascript

It's a reference book and yet free! You can read it online here, or get your own paperback copy of it. There's a decent amount of exercise on some it's chapters, and you can play around with it's Code Sandbox. The Hack Reactor suggest you to read chapter 1 - 5 before proceeding to their technical interview.

  • You Don't Know Javascript (YDKJS)

The free open source Javascript which available to public through gitHub. Tons of Javascript expert have been spending time contributing to this project, thus giving you insight on how deep this book might goes. You can get the paperback copy too through O'Reilly publishing.

Once you reach an intermediate state, you might find yourself need to find the perfect design pattern out there. The design that would gives your code the desired maintainability, reusability, and reliability to solve existing problems.

  • eJohn

I personally haven't check it's content, but if you consider so, please refer here. It did mention that it's an advance Javascript.

I'll gradually add this list by time.

Cheers :)