How to Use Backendless With React.js

React.js is one of the best and most popular front-end frameworks available for app builders. The barriers to entry in terms of understanding how to develop an app with React are very low, which is why many JavaScript developers choose the React library for web or mobile applications. It also works very well with a large number of data providers. Therefore, today we are beginning a series of articles about "How to use Backendless with ReactJS." In this series, we will familiarize you with a number of Backendless features, show you how to use our real-time database with the React-Redux store, show you how to deploy your app to Backendless File Storage, and demonstrate how to easily inject the into your React application.

In this article, we will start by creating a new Backendless App and building a simple React app. Our demo app will be an Address Book app, so to get started we will show how to load and display some data from the server. In the future, we will modernize the application by adding more functionality.

How to Build an iMessage Extension for a React Native App (Part 2)

In this post, I will show you how we built an iMessage extension by writing a bridge for our React Native-based mobile app. This approach took our team around two weeks to explore and might save you significant time if you have a similar intention. This is part two out of two (you can find Part 1 here). 

Project Recap

When we set out to build an iMessage extension for Lisk Mobile using React Native, we immediately hit an exciting challenge. As it turns out, when it comes to third-party applications, Apple likes developers to play by its own rules. If a company wants to benefit from the features of the tech giant's operational systems and rich user base, it needs to be built using Apple's own tools and programming language. iPhone's iMessage is definitely worth this hassle. It has proven to be a big hit since its release in 2016. Within the first six months, iMessage generated thousands of innovative in-messenger extensions including those created by Airbnb and Dropbox. Late in 2018, Mark Zuckerberg admitted this feature is one of Facebook's 'biggest competitors by far.' Since the release of Lisk Mobile during Lisk's Berlin meetup in October 2018, our team has been busy implementing features such as Face ID Authentication, as well as developing blockchain-specific solutions. Identifying the opportunity to extend the iMessage option for our users, we got to work on our own integration.

Geofencing Regions With JavaScript and HERE

When it comes to maps and location services, being able to see if a position is within a particular region is often an important business need. The regions being tracked are known as geofences and they're not difficult to produce and use.

In this tutorial, we're going to see how to create a geofence and then determine if a point falls within that geofence using JavaScript in combination with the HERE JavaScript SDK and HERE REST API.

JavaScript Generators and How They Work

What Are Generators?

  • Generators in ES6 are a new way of working with functions and iterators.
  • They appear to be a function but behaves like an iterator which simplifies the task of writing iterators.
  • They are different from a normal function, as they can stop mid-execution and then continue from where they stopped.
  • In layman’s terms, they are similar to the way we put a marker/bookmark in a page of the book we are reading. Then later we resume reading the book from that particular page instead of starting all over again. Here we acted as a generator function.
  • They can generate a series of results instead of a single value.

Generator Syntax

  • Creating a generator is similar to a normal function, with the difference that it requires a * between the function keyword and function name.
  • It allows any number of spaces or no spaces in between.
  • It uses the yield keyword to pause and resume execution.
  • Since it is just a function, we can use it anywhere just like we would with normal function, i.e. inside objects and class methods.
  • Basic syntax:
// All below formats are valid with spaces/no spaces in between function keyword, * and function name.
function * functionName() {
    // Your generator related codes here.
}

// OR below format.
function *functionName() {
    // Your generator related codes here.
}

// OR below format.
function* functionName() {
    // Your generator related codes here.
}

// OR below format.
function  *  functionName() {
    // Your generator related codes here.
}

// OR below format.

function*functionName() {
    // Your generator related codes here.
}

// Inside Class method.
class testClass {
    *functionName() {}
}

// Inside object
var testObject = {
    *functionName() {}
}

Yield Keyword

  • The yield keyword is used to return data and pause the execution of the generator.
  • Every time the generator encounters yield, it halts the execution at that point and returns the specified value. It then resumes the execution upon calling the next() method on the Generator object until it finds the next yield.
  • In the context of generators, we do not say that it returned a value. We say that it has yielded the value.
  • Using return inside a generator will set the done property to true, after which it cannot generate any more values. All the code after the return statement will not execute.
  • Syntax:
// Generator with yield. 
function * generator() {
    console.log('First execution.');
    yield 'Yield First execution, saved the state and exit';
    console.log('Second execution will be on next() call.');  
    yield 'Yield second execution, saved the state and exit';
}

const generatorObj = generator();

next() in Generators

  • The generator returns an object on which we can call next().
  • Every invocation of next() will return an object containing the returned value and the status of the generator's execution.
  • The value property will contain the value and the done property will return true or false for the generator’s execution status.
  • When done becomes true, the generator stops and won’t generate any more values.
{
    value: Any,
    done: true|false
}
function * generator() {
    console.log('First execution.');
    yield 'Yield First execution, saved the state and exit';
    console.log('Second execution will be on next() call.');  
    yield 'Yield second execution, saved the state and exit';
}

const generatorObj = generator();

// After below execution, generator will yield value, return below object and pause execution.
// {value: 'Yield First execution, saved the state and exit', done: false}
setTimeout(() => console.log(generatorObj.next()), 1000);

// After below execution, generator will yield value, return below object and pause execution.
// {value: 'Yield First execution, saved the state and exit', done: false} 
setTimeout(() => console.log(generatorObj.next()), 3000);

// After below execution, generator will yield value, return below object and close execution.
// {value: undefined, done: true}
setTimeout(() => console.log(generatorObj.next()), 5000);
  • The below screenshot shows the different states of a generator during its execution of how it gets "suspended" when it encounters the yield keyword, resumes when next() is called, and then gets closed after the execution is complete:JavaScript generators
  • If we use return then it will not execute any code present after the return statement. Sample code (JSFiddle link: generator with return statement):
  • function * generator() {
        console.log('First execution.');
        yield 'Yield First execution, saved the state and exit';
        return 'Execution ends here due to return and will not execute rest of the codes.';  
        // All below codes will not get executed.
        yield 'Yield second execution, saved the state and exit';
    }
    
    const generatorObj = generator();
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: 'Yield First execution, saved the state and exit', done: false}
    setTimeout(() => console.log(generatorObj.next()), 1000);
    
    // After below execution, generator will yield value, return below object and completes the execution.
    // {value: 'Execution ends here due to return and will not execute rest of the codes.', done: true}
    setTimeout(() => console.log(generatorObj.next()), 3000);
    
    // generator execution is already completed so it will just return value as undefined and done as true.
    // {value: undefined, done: true}
    setTimeout(() => console.log(generatorObj.next()), 5000);
  • We can also pass values to next().
    Sample code (JSFiddle link: next() with value passed):
  • function * generator() {
        console.log('First execution.');
        yield 'Yield First execution, saved the state and exit';
        console.log('Second execution will be on next() call.');  
        let passedArgument = yield 'Yield second execution, saved the state and exit';
        yield passedArgument;
    }
    
    const generatorObj = generator();
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: 'Yield First execution, saved the state and exit', done: false}
    setTimeout(() => console.log(generatorObj.next()), 1000);
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: 'Yield First execution, saved the state and exit', done: false} 
    setTimeout(() => console.log(generatorObj.next()), 3000);
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: "This is the passed value", done: false}
    setTimeout(() => console.log(generatorObj.next('This is the passed value')), 5000);
    
    // After below execution, generator will yield value, return below object and close execution.
    // {value: undefined, done: true}
    setTimeout(() => console.log(generatorObj.next()), 7000);

    Why Use Generators

    • Implementing Iterables:
      • Implementation of an iterator in JavaScript requires things to be done manually, like:
        • Creating an iterator object.
        • Implemeting the next() method.
        • Making a return object for next() in the proper format: { value: Any, done: true | false }
        • Saving the state.
      • The below sample code shows how hard it is to manually implement everything in an iterator.
      const iterableObj = {
          [Symbol.iterator]() {
              var counter = 0;
              return {
                  next() {
                      counter++;
                          if (counter === 1) {
                              return { value: 'step one', done: false};
                          } else if (counter === 2) {
                              return { value: 'step two', done: false};
                          } else if (counter === 3) {
                              return { value: 'step three', done: false};
                          }
                      return { value: '', done: true };
                  }
              }
          },
      }
      
      for (const val of iterableObj) {
          console.log(val);
      }
      • The below sample code shows how easy it is with a generator which handles most of the things on its own.
      function * iterableObj() {
          yield 'step one';
          yield 'step two';
          yield 'step three';
      }
      
      for (const val of iterableObj()) {
        console.log(val);
      }
    • Lazy execution: Generator helps to delay the evaluation of an expression until its value is required. So, if we don’t need a value, it won’t exist and is calculated only when we need it.
    • Memory efficient: It is memory efficient because we generate only the values that are required. We need to pre-generate all the values in case of normal functions and keep them in case we can use them later. But generators can defer the computation of any expressions/code until we need it.

    Limitations

    • Generators are one-time access only. Once you’ve exhausted all the values, you can’t iterate over it again. To generate the values again, you need to make a new generator object.
    • Generators do not allow random access with arrays. 

    I hope this post has helped you get a better grasp on  JavaScript generators and their basic functionalities.

    Happy coding!

    An Introduction to JavaScript/ES6 Arrow Functions

    Arrow Functions help programmers to write declarative code with JavaScript. While everyone may have different feelings about this addition to Javascript/ES6, whatever camp you belong to you, you will have to deal with variations of Arrow Functions.

    Why Do You Need to Know This?

    Theoretically, you don't need to learn to use arrow functions at all. You can do everything with good old "function" that you have been doing since you started writing JavaScript code. It could be advantageous in some cases, but you can get away without using them. But even if you don't use it right now, you might end up using arrow functions in the future or you might have to maintain code that was written by someone who loved using arrow functions. 

    React.js Context Tutorial: A Better Way to Store State?

    While creating a component in a typical React app, we end up creating layers of functional components and class components. Much of the time, we end up following a pattern where we pass props to a functional or class component from Grand Parents to Great Grand Children (referring to the hierarchy shown below). There are cases when props are not required at a certain level but are there just to be passed to another component.

    We can use React's context pattern to solve this problem. It's based on the Consumer Provider pattern, i.e. a producer stores the state and methods to manipulate the state and the consumer can access them whenever necessary. 

    Don’t Track too Much! Take Control of Your Analytics With ZK

    Foreword

    Tracking and Reporting are common business requirements today. Understanding how to properly integrate and use analytics in your web application is the first step to taking better control of it.

    In this article, we will discuss how the ZK framework helps take control of tracking in a ZK web app using an analytics provider such as Google Analytics. We will introduce how analytics work, and how to use it. Then, we will explore how ZK makes analytics integration easy and powerful in the context of a client/Java server web application, while still providing intentionality in our data collection instead of capturing every event indiscriminately.

    JavaScript Promises: The Definitive Guide, Part 1

    The single-threaded, event-loop based concurrency model of JavaScript deals with processing of events using so-called “asynchronous non-blocking I/O model.” Unlike computer languages such as Java, where events are handled using additional threads and processed in parallel with the main execution thread, JavaScript code is executed sequentially. In order to prevent blocking the main thread on I/O-bound operations, JavaScript uses a callback mechanism where asynchronous operations specify a callback – the function to be executed when the result of an asynchronous operation is ready; while the code control flow continues executing.

    Whenever we want to use the result of a callback to make another asynchronous call, we need to nest callbacks. Since I/O operations can result in errors, we need to handle errors for each callback before processing the success result. This necessity to do error handling and having to embed callbacks makes the callback code difficult to read. Sometimes this is referred to as “JavaScript callback hell.”

    Why Global Variables Shouldn’t Be Very Global

    One of the biggest blunders a JS developer can do make while writing code is declaring unnecessary global variables. Global variables are extremely helpful for programmers, but if they are not used carefully, they can rob the speed and efficiency of any browser.

    Short Note

    There are mainly two types of variables that are used in JS: local and global. Local variables are defined and used within a function, whereas global variables are defined for the function window. In short, until the code doesn’t terminate, global variables will be present, lurking in the background.