Javascript

Introduction

React Native allows you to write code for the iOS and Android platforms using the Javascript and React syntaxes. With this logic, you will want to re-use as much code as possible for both platforms. However, at one point, you will have to write code for a specific platform. In this article, we will see how React native makes this possible.

Continue reading React Native: Write code depending on the plateforms

Read more

Introduction

In my last article, I gave a quick overview of the Hyperledger Composer framework to build a business network with a private blockchain technology. I used a land registry network to show how the framework works. We then used a React application to use the REST API provided.

This time, instead of using the REST API, I made a little command line application using the Javascript API. The concept is simple. You enter commands in your terminal to trigger actions ( retrieve data, create assets and/or transactions ). We will re-use the same land registry network I used in the previous article.

Continue reading Private Blockchains: Hyperledger Composer Javascript API

Read more

blockchain

Introduction

Bitcoin and cryptocurrencies made a lot of noise lately. I have been rather disappointed by the turn the cryptocurrencies took, from an amazing concept to what seems just another way to make quick money ( or not… ).

But I became very interested by the technologies enabling cryptocurrencies, and obviously by the concept of a blockchain. The concept is fascinating, and not limited to Bitcoin and friends. We could imagine many applications for such a technology. So, in a proper developer manner, I decided to code one blockchain, or what I think is a blockchain, to understand better what it is.
Continue reading Trying to understand blockchain by making one!

Read more

Introduction

In the last few weeks, I was very intrigued by React native. I kept seeing more and more articles like this one, so I decided to take a deeper dive into React Native and actually use it, for real.

Meteor is the framework I use at work, and I now have some experience with it. I thought about connecting the React Native application with a Meteor back-end. This article will show you how to get things started.

Creating the Meteor app

First things first, we will create a Meteor application.

meteor create serverMeteor

For now, that is all we need. We’ll come back to that.

Creating our React Native app

I’ll use the very useful create-react-native-app tool. You can get more info on this, check this link. It will also explain how to use the Expo client app to see your work, very useful!

So, we run a command like this:

create-react-native-app reactFront

Now, you’ll have two folders. One named meteorServer that contains your Meteor application, and an other named reactFront where you will find your react-native application.

React-Native: Creating a simple PhoneBook

For the sake of brevity, we will create something simple. The user will have a form with two inputs. The first will take a name, the second a phone number.

After modifications, here is how App.js looks like:

import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';

export default class App extends React.Component {
  constructor(){
    super()
    this.state = {
      name: '',
      number: ''
    }
  }

  addPhoneNumber = () => {
    console.log(this.state)
    this.setState({
      number: '',
      name: ''
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.input}
          placeholder='Enter a name'
          onChangeText={name => this.setState( {name} )}
          value={this.state.name}/>
        <TextInput
          style={styles.input}
          keyboardType='numeric'
          placeholder='Enter a phone number'
          onChangeText={number => this.setState( {number} )}
          value={this.state.number}/>

        <Button
          onPress={this.addPhoneNumber}
          title='Save Phone Number'/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    marginTop: 20
  },
  input: {
    borderWidth: 2,
    borderColor: 'gray',
    height: 50,
    margin: 10
  }
});

I added two TextInput elements and a Button element. I also added some styles for the input. In React Native, we use StyleSheet.create({}) to control styles. Or you could style use the inline objects as in React.

On my iOS simulator it looks like this:

Ok, for now, when we click ( or tap ) on the button. Nothing happens. It logs the values in the console and reset them. Let’s move on to the back-end.

Meteor: Preparing the method and publication

Go to the folder where your Meteor application is located. Mine was called serverMeteor.

Let’s create a /imports folder, and inside this /imports, we’ll add an /api folder. Just to follow the proper Meteor conventions.

Here is the plan: we will create a Meteor method that our React Native app will call when we click on the Save Phone Number button. This method will save the name and the number to the Meteor mongo database.

Then, we will create a publication that our React Native application will subscribe to. It will simply return all the entries we have. Let’s go!

In /imports/api/, let’s create a PhoneNumbers.js file that will hold our small back-end logic.

export const PhoneNumbers = new Mongo.Collection( 'phoneNumbers' )

Meteor.methods({
  addPhoneNumber( data ){
    PhoneNumbers.insert({
      name: data.name,
      number: data.number
    }, err => {
      if (err){
        return err
      } else {
        return null
      }
    })
  }
})

Meteor.publish( 'getAllNumbers', () => {
  return PhoneNumbers.find({})
})

Nothing fancy here. We create our collection, our method addPhoneNumber and our publication getAllNumbers. And that’s it for Meteor. Let’s make the two applications talk to one another.

React Native: Adding react-native-meteor

Go back to the React Native folder. We will use the react-native-meteor package to connect both applications.

npm install --save react-native-meteor

Here are the changes we need to make:

  • Call the addPhoneNumber method when we click our button.
  • Subscribe to our getAllNumbers publication
  • Display the numbers in a list
  • Make sure our React Native app is aware of our Meteor application.

Let’s start with the method call. If you’ve work with Meteor/React before, this will look very familiar:

// In our App component
addPhoneNumber = () => {
    const data = {
      number: this.state.number,
      name: this.state.name
    }

    Meteor.call('addPhoneNumber', data, err => {
      if( err ){
        console.log( err )
      } else {
        this.setState({
          number: '',
          name: ''
        })
      }
    })
  }

Next, let’s subscribe to our publication. For this, we will wrap our App component in createContainer provided by react-native-meteor. Let’s import it at the top of our file:

import Meteor, { createContainer } from 'react-native-meteor'

Good, now we will NOT export our App component, but the createContainer wrapper. Like so:

// The App Component will be defined above like so:
// class App extends React.Component{ ... } 

export default createContainer( () => {
  Meteor.subscribe('getAllNumbers')
  return {
    phoneNumbers: Meteor.collection('phoneNumbers').find({})
  }
}, App) // Need to specify which component we are wrapping

Ok, that’s done. So we will get the phone numbers in a nice array. We will display them in a list. Nothing fancy, we will use the FlatList component. Don’t forget to import FlatList from react-native. Our render function will look like so:

// Still in the App component my friend
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.input}
          placeholder='Enter a name'
          onChangeText={name => this.setState( {name} )}
          value={this.state.name}/>
        <TextInput
          style={styles.input}
          keyboardType='numeric'
          placeholder='Enter a phone number'
          onChangeText={number => this.setState( {number} )}
          value={this.state.number}/>

        <Button
          onPress={this.addPhoneNumber}
          title='Save Phone Number'/>

        <FlatList
          data={this.props.phoneNumbers}
          keyExtractor={(item, index) => item._id}
          renderItem={({item}) => (
            <View>
              <Text>{item.name} || {item.number}</Text>
            </View>
          )} />
      </View>
    );
  }

FlatList takes the array of data and loops through it in the renderItem function. I’m just displaying the name and the phone number. keyExtractor is used to create keys for each element we render in this list, just like React needs in the web. Each key will be the ObjectID returned from MongoDB.

Finally, let’s make sure our React Native application knows where to get those informations:

//I have only one component anyway...
  componentWillMount(){
    Meteor.connect('ws://localhost:3000/websocket')
  }

We use the connect method from react-native-meteor.

Note: Because I am only using the iOS simulator here, I can use localhost. If you use the android simulator, you will need to use the IP address of your machine ( 192.168.xx.xx:3000/websocket for example).

Clicking on the Save Phone Number button will populate the database in our Meteor application. Our subscription to the publication will retrieve the informations and display them!

Just a final picture to show you how it looks on my iOS simulator:

Well, there you have it. You can now connect a React Native application to a Meteor application without a problem. Have fun!

Warning: It seems that using npm5 with create-react-native-app is buggy and doesn’t work properly. You should probably use npm4 or yarn to make sure you don’t encounter any problems for now.

Read more

meteor logo

Introduction

Meteor has become the go-to Javascript framework for our team. We use it in combination with React on the front-end. I thought I would write a quick tutorial to get started with Meteor + React. In addition, I’ll also touch on FlowRouter for the routing. If you do not have Meteor installed yet, you can follow the instructions from this page
Continue reading Meteor, React and FlowRouter: Quick Setup

Read more

crazy homer simpson

Introduction

This is just a little article to share a problem I encountered. I was tasked with building a CRM and transactions had to be filtered by date. Nothing fancy about all this. You check if the transaction’s date is between two other dates the user gives you ( a start date and an end one ).

The code

Well, here is how the code looked before I managed to solve it. I was using React with this code. I used the popular javascript library moment.js to work with dates.


renderTransactions(){
    return this.props.transactions.filter( transaction => {
        const start = moment(this.state.startDate)
        const end = moment(this.state.endDate)
        const tDate = moment(transaction.date)

        return tDate.isBetween(start, end) // Compare dates here
    })
    .map( ( transaction, i ) => {
        transaction.date = moment(transaction.date).format('DD/MM/YYYY')
        return (
            
                {transaction.amount}
                {transaction.date}
                {transaction.client}
            
    })
}

// etc.. etc...

Ok, can you see where the problem is? The first time the component renders, everything is fine, the dates are properly filtered. But, as soon as I modify the dates, nothing works anymore…

The problem was here:

transaction.date = moment(transaction.date).format('DD/MM/YYYY')

See how stupid that is? I mutate the state of my array with this line. On the next render, the date field is not longer a Date object that the moment library can work with, but a String…

Solving it, and restoring my sanity…

Take one:

Don’t use this.props directly. If I used a reference to this.props.transactions in my function, the problem wouldn’t have happened. Every time the function would run, a fresh copy of this.props.transactions would be used. Even if I kept the problematic line with the direct mutation, it would work.

Take two:

Immutability. Don’t mutate the state of your application directly. This line would have solved everything:

const date = moment(transaction.date).format('DD/MM/YYYY')

Done… Problem solved.

Conclusion

I’m just writing this to make sure I don’t make the same stupid mistake again. I spent way to much time on this… I’m tired and I hate programming.

Read more

Introduction

Aaaaah, prototypes… How many blog posts did you read where prototypes are listed as a must-know caracteristic of the language? How many times senior developers told you about prototypal inheritance? I’ve spent quite some time avoiding to learn more deeply about this thing. I got tired of procrastinating, so I wrote this thing.

Continue reading No, not inheritance, please call me delegation…

Read more

With ES6, we were given a new tool: generators. In a normal function, there is only one entry point: the invocation of the function itself. A generator allows you to pause the execution of a function and resume it later. Generators are useful when dealing with iterators and can simplify the asynchronous nature of Javascript.

Syntax

So, how would we define a generator, compared to a normal function? You declare a generator function by using the * ( asterisk ) operator after the function keyword:

function* awesomeGenerator(){
  //code
}

To pause the execution inside the generator, we use the statement yield:

function* awesomeGenerator(){
  yield 'Hey friend' // We pause the execution here
  console.log('Back again') // When we resume, we are here
}

next() method

A generator gives you a next() method, which is used to start/resume the execution. This method returns an object with two keys:

{
  value: [ yielded value ],
  done: [ true if we reach the end]
}

Let’s see a very simple generator in action:

function* groceriesGenerator(){
  yield 'Eggs'
  yield 'Tomatoes'
  yield 'Milk'
  return 'Paper Bag'
}

const groceries = groceriesGenerator()

console.log(groceries.next()) // [1]
console.log(groceries.next()) // [2]
console.log(groceries.next()) // [3]
console.log(groceries.next()) // [4]

// [1] { value: 'Eggs', done: false }
// [2] { value: 'Tomatoes', done: false }
// [3] { value: 'Milk', done: false }
// [4] { value: 'Paper Bag', done: true }

At our first groceries.next() call, our groceriesGenerator reached our first yield statement and paused, returning the value Eggs to the caller. Our second next() resumed the execution at the second yield statement, pausing it again and returning Tomatoes

Our last next() terminates the generator, returns Paper Bag and sets done to true.

As iterators

In the introduction, I said that generators could help to implement iterators. Let’s see an example:

function* iterationGenerator( arr ){
  for( let i = 0; i < arr.length; i++ ){
    yield arr[i]
  }
}

const iterator = iterationGenerator( ['John', 'Sarah', 'Joe', 'Emily'])

let current = iterator.next()

while( !current.done ){
  console.log( current.value )
  current = iterator.next()
}

// John
// Sarah
// Joe
// Emily

In this example, you can see how the state of the generator is maintained accross invocations. Whne we resume the execution by calling next(), the variables and loops are the same.

Pass values back to generators

Finally, you can also pass a value back to a generator. Here is a example:

function* twoWayGenerator(arr){
  for( let i = 0; i < arr.length; i++ ) {
    const symbol = yield 
    console.log(`${arr[i]} ${symbol}`)
  }
}

const prices = twoWayGenerator([10, 23, 12])

prices.next()
prices.next('€')
prices.next('£')
prices.next('$')

// 10 €
// 23 £
// 12 $

Here, our first next() will not print anything because we pause the execution before the first console.log. The second next() is called with an argument. This argument is provided as the returned value of the yield statement. We store this value inside the symbol variable and use it next.

You can also force a generator to throw an error:

prices.next()
prices.throw( new Error('Invalid Amount'))

//  const symbol = yield
//                   ^
//  Error: Invalid Amount

That’s it for a quick and dirty introduction about generators. In the next article, we will go a bit deeper and explore how generators can help us control the asynchronous flow of Javascript.

Read more