CI/CD with gitlab runner – Automatic app deployment.

Posted On 02 October 2020 ( 13.1 Minute Read )

gitlab-ci-cd
gitlab-runner

Before getting in to more details and seeing the strategies we can use to set up a CI/CD pipeline in Gitlab using gitlab runner, let’s first see some details and points about Continuous Integration and Continuous Delivery (CI/CD).

What is continuous integration ?

In short terms it is the process of merging together all new codes by programmers.This merging together is usually in a shared repository. But the process can be further advanced by adding test scripts and running other scripts like building production apps.

What is continuous delivery ?

Continuous delivery states that applications can be automatically deployed on a server. The servers can be either production or staging. This usually happens when a new code or feature is pushed to the repository.

Why Is CI/CD Important ?

Let’s list some points down below to show the importance CI/CD in our application development process

  • Consistency: CI/CD gives us consistency in the overall development life cycle by giving us a specific automated testing and building process.
  • Error Reduction: CI/CD can reduce the errors that can be caused by developers in doing manual deployment and tests.
  • More time spent on actual development : It will reduce the time and energy that will be put in to place to do manual deployments. .This way we can put our resources in actual coding or testing.
  • Happy Developers : Running the same command every time you make a change can some times be boring. By automating our deployment we can reduce repetitive tasks and make releases more appealing.

Integrating CI/CD with gitlab to your existing application

When it comes to CI/CD there could be multiple service providers, but we chose to implement our CI/CD with gitlab in the ease of use it provides and also the lower learning curve that comes with it. And I have to admit using the same service provider for handling you code repository and your CI/CD feels consistent and reliable.

In the tutorial below we will see how we can add a CI/CD pipeline to an existing application running on docker and NodeJS. We will then deploy the application to a server running Ubuntu 18.04 . Here is an example of an existing code base running on docker, NodeJs, Express and Mongoose boilerplate. Check out this post on some basic of docker if you are unfamiliar.

The important thing to note here is CI/CD is not limited to only Node.Js applications, you can pretty much use it in any programming language or framework. Once you are up an running you will be able to run any command on your server to either install packages, build your application and run your application.

The First thing you need is a server where you can SSH in to and run commands this can either be a VPS or your own dedicated server. In our case a VPS running Ubuntu 18.04.

Install GitLab runner

GitLab runner is the program that will receive changes from your repository, run your commands from .gitlab-ci.yml file. It then send back the results of your commands back to GitLab. You can read more about it from the official documentation.

Add the official GitLab runner repository

Run the command below that will retrieve gitlab’s official bash script to add gitlab runner repository to your system based on your architecture.

$ curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash

Next run the apt install command to install gitlab runner on your system.

$ sudo apt-get install gitlab-runner

After that command runs successfully your system will now be able to run gitlab-runner commands. Run the next command to make sure gitlab runner is installed in and view some description about our installation.

$ gitlab-runner -v

Register the gitlab runner next. This will integrate your gitlab runner with your repository on gitlab.

$ sudo gitlab-runner register

After running the register command you will be prompted to fill out some information regarding your repository and some other information. The prompts in chronological order are listed below

  1. The gitlab-ci coordinate URL. You can find it in GitLab repository – -> Settings –> CI/CD –> Runner Page.
  2. The gitlab-ci token. This information is also found in the setting of your CI/CD just like the gitlab-ci coordinate URL,
  3. The gitlab-ci description. You can write some description about this specific runner here.
  4. The gitlab-ci tags. Pay attention to the tag you write here gitlab will be matching which step to use based on this. It cab be something like myapp-production . You will be using this tag later on when we write the ,gitlab-ci.yml configuration file.
  5. Finally the executor. Use shell executor here as we are going to be running shell commands from our configuration file.

The next thing we need to do is to make sure our gitlab-runner user will be able to run sudo commands with out entering a password. Out gitlab-runner user is created during installation so there is no further configuration needed to add the user. Open your sudoers file using nano terminal editor.

$ sudo nano /etc/sudoers

Add the line below to the end of the file which specify that no password is will be required for the sudo user. And finally save the file.

gitlab-runner ALL=(ALL) NOPASSWD: ALL

This will conclude the configuration needed to set up gitla-runner on your server. Next we will see how we can write a configuration file in our repository, This file will communicate with our gitlab-runner and tell it which commands to run,

Adding .gitlab-ci.ym file

The gitlab-ci.yml file is a configuration file which gitlab will determine the structure of our pipeline and the commands the gitlab-runner will execute. We can also specify what decisions to make when a certain condition happens like when a process succeeds or fails. Below is a simple example of a .gitlab-ci.yml file. The commands will consist of running a dockerized Node.JS application with the help of docker-compose. Make sure to install both docker and docker-compose to your server if you are using this stack.

image: docker:latest

services:
  - docker:dind

# List stages in the pipeline, you can add other steps like test here
stages:
  - deploy

step-deploy-production:
  stage: deploy
  before_script:
    - export DYNAMIC_ENV_VAR=PRODUCTION
  only:
    - master
  tags:
    - myapp-production   # The tag you used when registering gitlab-runner
  script:
    - echo setting up env $DYNAMIC_ENV_VAR
    - sudo docker image prune -f
    - sudo docker-compose down
    - sudo docker-compose build --no-cache
    - sudo docker-compose up -d

This simple file contains the minimal configuration needed to deploy a simple dockerized application. The most important parts are stages block, the only block and the script block.

In the stages block we list out the stages our pipeline will have. In the case of this example we only have a deploy stage but you can also add other stages like test and build to your pipeline.In the step-deploy-production block on line 10 we configure our deployment step, like telling the runner only to run this step on master branch on line 14, which tag to use to map to our gitlab-runner on line 16 and what scripts to run on our server on line 18.

After pushing this file to your repository your gitlab-runner will automatically start executing commands on your server to deploy your application. In the case of our example above the gitlab runner will start only when there is a push or merge to our master branch. You can view the status of your pipeline in Gitlab Repositor –> CI/CD –> Pipeline then select the pipeline you are interested in whether it is running, successfull or failed.

You can read more about .gitlab-ci.yml configuration file from the official documentation here.

Finally make changes, commit and start pushing features to your repository and your server !!

AdminBro – Part one

Posted On 23 September 2020 ( 7.2 Minute Read )

This blog is the getting started guide for AdminBro, react based admin panel for node js application. In this blog, we are going to create a demo app where an admin can manipulate users’ and companies’ data using an admin panel created by AdminBro. I am going to divide this tutorial into different parts because of its length. The code for each part will be pushed to a separate branch on Github[https://github.com/zelalem-12/adminbro-tutorial].

Note: This blog is for those who are already familiar with node js with express framework, mongoose and react.

For the last couple of years, I have been working mostly on Node projects. Since then, I have been looking for a role-based admin panel for my node js applications. Recently, I came across AdminBro, which uses your existing framework to render its routes. It is really useful because it not only allowed me to add an admin panel in a very short time frame but also provided various customizing options. More importantly, AdminBro allows you to manage your database resources. It supports Mongoose(MongoDB ORM) and Sequelize for your Relational Database ORMs and It works flawlessly with Express.js and Hapi.js. Not just that, AdminBro can be integrated with any Node.js Framework. As defined on AdminBro home page,

AdminBro is An automatic admin interface that can be plugged into your application. You, as a developer, provide database models (like posts, comments, stores, products, or whatever else your application uses), and AdminBro generates UI which allows you (or other trusted users) to manage content.

Why should you use it:

  1. Supports both relational(Sequalize) and non relational(mongoose) Database Models
  2. Built on the modern stack: Node.js, React.js, Styled-components
  3. Supports heavy customization
  4. Its awesome look

……………………………………………………………………………

In this part the blog, we will be able to

  1. Create app and models using express and mongoose
  2. Install and integrate AdminBro

In the next part, we will be doing more customization to our admin panel.

Create app and models

Before starting with AdminBro you must have an Express.js application with your models defined. So, in the first section, we are going to set up a Node.js Server with Express.js and also define our models in mongoose.

Create a simple express application

const express = require(‘express’)
const bodyParser = require(‘body-parser’)

const app = express()
app.use(bodyParser.json())

app.get(‘/’, (req, res) => {
res.send(‘Hello World’)
})

//…
// Your Routes
//…

const PORT = 3000
app.listen(PORT, () => {
console.log(? Server started on PORT: ${PORT})
})

Create your database model To keep things simple we are just building a User Model in mongoose

const mongoose = require(‘mongoose’)

const userSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
avatar_url: { type: String },
bio: { type: String }
})

module.exports = User = mongoose.model(‘User’, userSchema)

Add your models in your app and Connect to MongoDB

Connect to your MongoDB database in your app.js file. To do this add the following code in your app.js

Import MongoDB

const mongoose = require(‘mongoose’)

// Connect to MongoDB
mongoose
.connect(YOUR_MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log(‘? MongoDB Connected…’)
.catch(err => console.log(err))

Install and integrate AdminBro

Install the AdminBro and necessary adapter(s)

npm i admin-bro admin-bro-expressjs admin-bro-mongoose express-formidable

Create an admin.js file to Keep your AdminBro Configurations

const AdminBro = require(‘admin-bro’)
const AdminBroExpress = require(‘admin-bro-expressjs’)
const AdminBroMongoose = require(‘admin-bro-mongoose’)

const User = require(‘./model’)

AdminBro.registerAdapter(AdminBroMongoose)
const adminBro = new AdminBro({
rootPath: ‘/admin’
resources: [
{
resource: User,
options: {
// check the documentation for options you can use
}
}
],
})

module.exports = adminRouter = AdminBroExpress.buildRouter(adminBro)

Add the AdminBro Router

Add the AdminBro Router in your app.js

app.use(‘/admin’, require(‘./admin’))

Start the server and test

Now start your server and go to https://localhost:3000/admin or to your local server’s URL(If you’re using different configuration).

You can see the AdminBro dashboard with your Models on the Left Sidebar. You can now perform all operations on your data with the AdminBro Panel.

In this part, we are done with the introduction, setup, and integration. In the next part, we will add customizations that unlock best the features of AdminBro.

Documentation: https://softwarebrothers.github.io/admin-bro-dev/

GitHub: https://github.com/SoftwareBrothers/admin-bro

NPM: https://www.npmjs.com/package/admin-bro

Always Try to use Memoized Components in React

Posted On 23 September 2020 ( 12.9 Minute Read )

Because of the fact that whenever the states and props of react components or their parent components change the component and its child component will re-render, it will create a huge performance problem or might lead to infinite loop if not watched carefully and implemented with such appropriate caution.

Memoizing in React is a performance feature of the framework that aims to speed up the render process of components. The technique is used in a wide spectrum of disciplines, from game engines to web applications.

This article explores memoization techniques within React.


Memoizing is a well known concept in computer programming, aiming to speed up programs by caching results of expensive function calls and re-using those cached results to avoid repeating those expensive operations. While Memoizing often-times saves processing cycles, there is a limit to how much it can be used — this is of course dictated by a system’s memory limits.            

                
When it comes to React, we are caching the result of a component’s render() method — or simply the returned JSX of a functional component.


It is wise to consider how much of your application will be cached via memoizing Since mobile devices will inevitably have less memory to utilize than laptop or desktop counterparts.

here are two lists of ways that you can introduce memoization in react

1. Memoization with useMemo() and useCallback() hooks

Memorize hooks need to remember data or functions that:

  1. Might cause re-render when re-rendering is not needed
  2. Preserve or cache data or function so new copies are not created.
  • useMemo() returns a memoized value, 
useMemo(()=>{},[deps])
  • whereas useCallback returns a memoized callback
useCallback(()=>{},[deps])


Both React.useMemo and React.useCallback receive a function as its first argument and a dependencies array as the second one. The hook will return a new value only when one of the dependencies value changes.


The main difference is that React.useMemo will call a function and return its result while React.useCallback will return a function without calling it. The Memoized hooks caches the computationally expensive functions data and return them a given one of the dependency array is changed. 

2. Memoization with react Reselects


Well most of the time we often use reselectors in react state management tool with selectos. But before going to reselectors we have to understand what selectos are.


At their most simple, Selectors are simply functions that are used to select a subset data from a larger data collection. Basic selectors (i.e simple functions that return a subset of data) are beneficial because they encapsulate knowledge of where to find that particular subset of data, they are also reusable and flexible


Selectors:


1) Have knowledge of the whereabouts or path to find a particular subset of data and
2) Return with the requested subset of data


Why Use Reselect to Create Selectors?


The short answer is: for performance as Reselect provides a wrapper for creating selectors that are memoized.


The definitions of selectors that you’ve seen so far have only been responsible for retrieving data as it appears in the redux store. This would only likely be enough in small apps where the data that app needs can be found directly in the store. However, in larger and more complex apps, it’s advisable to keep the store with minimal amount of information as it cuts down on repetition and generally helps to avoid highly nested data that results in more complex reducer logic. This is especially relevant for apps that are structured with a normalized store. The biggest benefit of Reselect is that selectors created with the library are memoized and therefore will only re-run if their arguments change.


here is an example of selectors obtaining a specific data from redux state:                        
here a selector gets the belt data from shop store,


//selector.js
// Note: selectors are usually created in a relevant reducer file or a separate selectors file
const getBelts = (state) => state.shop.items.belts;
class DisplayBelts extends React.Component {
render() {
return this.props.belts.map(belt => );
}
}
// and specify the result of selectors data to props
const mapStateToProps = state => {
return {
belts: getBelts(state)
}
}


By doing this we encapsulate knowledge of where to find that particular subset of data, they are also reusable and flexible. But if we ask the selector to give us a data that is not different from the previous one the selector would have to go again and get the data for which it doesnt have to do, because it can easily cache the data in a memory and read  that cached data from memory the next time it is asked the get that data. This way it would a huge amount of computation, time and keeps the react  component from rerendering. This is a place to use Reselect


Reselect offers up a function called createSelector() that’s used to create memoized selectors

import { createSelector } from 'reselect'
const shopItemsSelector = state => state.shop.items
const taxPercentSelector = state => state.shop.taxPercent
const subtotalSelector = createSelector(
shopItemsSelector,
items => items.reduce((acc, item) => acc + item.value, 0)
)
const taxSelector = createSelector(
subtotalSelector,
taxPercentSelector,
(subtotal, taxPercent) => subtotal * (taxPercent / 100)
)
export const totalSelector = createSelector(
subtotalSelector,
taxSelector,
(subtotal, tax) => ({ total: subtotal + tax })
)
To retrieve state in a component
import {totalSelector} from '/selector'
import {createStructuredSelector} from 'reselect'
class Inventory extends React.Component {
render() {
return The shop's total inventory is: ${this.props.inventoryValue}
}
}
const mapStateToProps = createStructuredSelector({
inventoryValue: totalSelector()
})


Memoizing Considerations
  • To use these APIs effectively, consider the following points to ensure your                        
    apps remain bug free while leveraging the performance gains of Memoizing:
  • Side effects (anything that affects something outside the scope of the                      
    function being executed) should not be performed in a memoized function.                    
    Leave this to the commit phase of the component, after its render phase has                          
    completed execution
  • Memoizing is performed in the render phase of a component, and side                        
    effects should typically be used in componentDidMount,            
    componentDidUpdate, and componentDidCatch with class components, or            
    useEffect with functional components
  • Use the Profiler to record the performance of your app before and after                          
    Memoizing. If the performance gains are not considerable, it may be worth                      
    removing the added complexity Memoization brings in certain areas of your                    
    app where there is not a huge performance gain, freeing up more memory and                         
    decreasing boilerplate
  • Compartmentalise a component into child components to leverage                
    memoization if you need to, such as in forms whereby static components such                       
    as buttons, labels and icons may be combined with dynamic components that                      
    need re-rendering, such as with validation. Separate these and memoize                  
    where possible — this is especially useful with complex SVG icons that contain                        
    a lot of markup

Web development in Ethiopia using Kubernetes

Posted On 21 September 2020 ( 8.5 Minute Read )

Why is it important we discuss Kubernetes in Ethiopia.

The main struggle in Web development in Ethiopia is a proper server infrastructure. If you have been at any governmental agencies to get any kind of work approved you probably have stayed for hours waiting for a system to get back online. One of the main reason for this kind of issue is the servers running one version of application. Whenever a bug or uncaught error is found in the server the entire city waits for the servers to restart. This phenomenon is also known as system shortage(system yelem). By creating a stable infrastructure we can minimize the number of hour spent waiting in line.

What is Kubernetes ?

The name Kubernetes originated from Greek meaning pilot, This software released by google as an open-source software in 2014 allows one to freely manage containerized applications and services.

A simple way to view it is to compare it to a symphony orchestra. Where there is one conductor instructing in who, how high and when each musician and instrument should play.  Each instrument and musician represents a containerized application or service.
The conductor also called the master node will instruct the musicians in kubernetes terminology called pods, services, ingress to work together in a perfect harmony. 

Kubernetes makes it easy to manage hardware resources, scale applications and manage release. With almost no downtime it is a good way to roll out a new version without system shortage. It also solves the Hardware shortage by only allocating resources to the application that is currently in need of it. No more system shortage  and smoother web development in Ethiopia.
Without going deep into how it works we will discuss the main idea of kubernetes and why we use it in our development process in Addis software.




Recommend to installing minikube for testing kubernetes on local development.

Kubernetes cluster
A cluster is network of virtual or physical machines known as nodes. Nodes are designated hardware space to run the kubernetes application and all the applications running on each node. Each application runs wrapped within temporary VMs called pods. A promotion assigned to one of the nodes to be a master node. A kubernetes cluster contains a masted node, at least one worker node, pods running inside each node

Master node

Main task is to  automatically handles scheduling the pods across the Nodes in the cluster from a given rule    

kubectl describe node <insert-node-name-here>

Deployment

Is Kubernetes api to manage a deployment  and allows you to describe an application’s life cycle, such as which images to use for the app. An example of a simple configuration file. 

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      run: my-app
  template:
    metadata:
      labels:
        run: my-app
    spec:
      containers:
      - name: hello-app
        image: gcr.io/google-samples/hello-app:1.0



To run the above deployment save the above snippet in a yaml file and run kubectl apply -f deploymentFileName , now you have created a deployment

To check the status of the deployment run kubectl describe deployment [DEPLOYMENT_NAME]. If you have forgotten your deployment name then you can run  kubectl get deployments to view a list of deployments. When a deployment is done it will create a pod running your application. When it’s time for you to scale up your application you can simply run the following command with the number of replicas you want to create kubectl scale deployment [DEPLOYMENT_NAME] –replicas [NUMBER_OF_REPLICAS] and  to remove a deployment kubectl delete deployment [DEPLOYMENT_NAME]

Pods

A pod is an isolated space where a containerized application runs in, it is viewed as a minimal running unit. it’s also mostly viewed as a temporary unit rather than a permanent one. It is also considered as the final resting place for your application code. Each pod is assigned an id, internal and external ip, and the containers will share the pods networks space. 

Once a deployment is done, you should be able to see the pod list by running kubectl get pods.

  • Pending: a pod have been accepted by kubernetes master and is in progress
  • Running: a deployment successfully started a pod
  • Succeeded: a pod is successfully terminated and will not be started
  • Failed: a container within the pod have some kind of error and could not be started
  • Unknown: the status of the pod is unknown

Service 

Service is kubernetes api to manage a running containers network, as pods are created and destroyed depending on the master node instruction a service main task id to track and manage the network for each pod or set of replicas.

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376

The above example shows a simple service that looks into all pods running with a label called MyApp and designate a TCP network port 9376 to those pods port 80

Ingress

Is kubernetes api to connect the external world to each specific service. 

Finally

Use Kubernetes to enhance your application and platform in web development in Ethiopia

Containerise everything!! : using docker in Ethiopia

Posted On 20 March 2020 ( 8.2 Minute Read )

You might have come across buzzwords such as containerization, docker and wondered what all the fuss was about. And why it is important to use docker in Ethiopia. Well, This tutorial series is just what you need to join the conversation. We will look through the basics of docker and why it might be useful to your workflow. Not only that by the end of this series you will be able to containerize your applications and get them ready for deployment.

What exactly is Docker?

Docker is a containerization platform that packages your app and all its dependencies together in the form called a docker container to ensure that your application works seamlessly in any environment. This environment might be a production or staging server. Docker pulls the dependencies needed for your application to run from the cloud and configures them automatically. You don’t need to do any extra work. Below are some benefits of Using docker

1. It is cost-effective: It takes fewer resources to run your production application. And an even fewer team of developers to maintain it. The biggest driver of most management decisions when selecting a new product is the return on investment. And docker has proven to be a very efficient option.


2. Standardization & productivity
: Docker containers ensure consistency across multiple developments, release cycles and standardizing your environment. One of the biggest advantages of a Docker-based architecture is standardization. Docker provides repeatable development, build, test, and production environments. Standardizing service infrastructure across the entire pipeline allows every team member to work on a production parity environment. By doing this, engineers are more equipped to efficiently analyze and fix bugs within the application. This reduces the amount of time wasted on defects and increases the amount of time available for feature development. Another key use for docker in Ethiopia

3. Compatibility & maintainability: Eliminate the “it works on my machine” problem once and for all. One of the benefits that the entire team will appreciate is parity. Parity, in terms of Docker, means that your images run the same no matter which server or whose laptop they are running on. For your developers, this means less time spent setting up environments, debugging environment-specific issues, and a more portable and easy-to-set-up codebase. Parity also means your production infrastructure will be more reliable and easier to maintain.

4. Rapid Deployment: Docker manages to reduce deployment to seconds. This is because it creates a container for every process and does not boot an OS, unlike virtual machines. Data can be created and destroyed without worry that the cost to bring it up again would be higher than affordable. Also by sharing container reduce dependency install time while using slow network making more use of docker in Ethiopia

5. Continuous Deployment & Testing: If you need to perform an upgrade during a product’s release cycle, you can easily make the necessary changes to Docker containers, test them, and implement the same changes to your existing containers. This sort of flexibility is another key advantage of using Docker. Docker allows you to build, test and release images that can be deployed across multiple servers and cloud services like Kubernetes. Even if a new security patch is available, the process remains the same. You can apply the patch, test it and release it to production.


5. Security
: And the last benefit of using docker is — security. From a security point of view, Docker ensures that applications that are running on containers are completely segregated and isolated from each other, granting you complete control over traffic flow and management. No Docker container can look into processes running inside another container. From an architectural point of view, each container gets its own set of resources ranging from processing to network stacks.

Now it’s time to get our hands dirty.  The first thing you need to do is install Docker on your own system and to do that just follow the official guidelines here.

After you have done that clone this sample Project locally. It is a simple Nodejs express server that we are going to containerize using docker. Run the following instructions to clone the repo and start it locally

#clone repo
git clone https://gitlab.com/Dagmawi-A/starterproject.git 

#cd into project directory 
cd starterProject 

#install project dependencies 
npm  install 

The next step is going to be to build our docker image and run it. Don’t be intimidated if the terms seem unfamiliar. We will go in-depth in part two of this tutorial.
Run the commands below

#build our docker image
docker build -t <your-name-here>/sampleproject:v1

#run our docker image and expose ports
docker run -p 8000:8000 <your-name-here>/sampleproject:v1

Now that we have got our application running in our Docker container we can access it locally in our browser. Just go to this link.

Congrats you’ve just created your first docker container. Stay tuned for part 2 !!

React.js Let’s Hook part 2

Posted On 07 February 2020 ( 3.7 Minute Read )

React.js Let’s Hook part 2

this is the continued part form our last blog in React.js Let’s Hook, If you didn’t read that, I suggest you do so here

so in this blog today, We are going to talk about Hooks in detail and proceed what we have started last time. Let’s get to it!

From our last blog, we have written code like the one blow and promised to explain it in the next blog ( i.e this one ).

Here is the code, in the section below we are going to dissect the code and understand what hooks are and how they are different from the class-based component

import React from 'react';
function OurFirstHook () {
const [clicked , setClicked] = React.useState(0);
const clickedHundler = (event) => {
     setClicked(clicked+1);
}
   return (
        <div>
          <Button onClick={clickedHundler}> 
           {`button clicked ${clicked} times`}
          </Button>
        </div>
         )
}
export default OurFirstHook

In the code above as you can see there is no class. and we have used some strange word ‘ useState ‘ which is accepting a value! well, let’s try to understand how this is different from class and how we are using state.

React Hooks enables you to have state in your functional component as if they were class components! This shouldn’t be a surprise since everything in javascript is a function. a function having a state is not a different thing. but comparing to what was it is pretty different.

React hooks enable state in using a new hooks API called ‘useState’. use state expects an initial value, as classes also expect the same for their state.

const [clicked , setClicked] = React.useState(0);

But hooks also have a set state function within every state you declare. for example in the code above we have setClicked declared with clicked to enable simplifying things and also its good to not that we should manipulate simple states using useState , if we have more complex states its better to use useReducers or redux.

when referencing a hook state

return (<div>
          <Button onClick={clickedHundler}> 
           {`button clicked ${clicked} times`}
          </Button>
        </div>)

we will dive into more advanced react Hook features in the coming blogs but till then happy coding from Addis software

Getting started with react-native

Posted On 01 January 2020 ( 4.9 Minute Read )

react native
react native

Getting started With React Native

What is react native

If you are just getting started with React I suggest reading those blogs in Addis Software website Getting started with react.js and also hooks


React native is a new way of putting your ideas to people’s hands in a short time. chances are If you are a developer, you already are familiar with javascript or could be an expert with it.

well, mobile development wasn’t easy for everyone. we use to struggle even to set up the environment rather than finishing the application in a given time. All that struggle looks to bear fruit, peoples irritation seems to build the greatest pain killer in mobile application development history, here it goes, drum roll please, ‘REACT-NATIVE‘.

React native has shifted the way we used to look at mobile application development. It has shifted our focus from learning the language to building an awesome experience for our users with the most known or famous language on the planet Javascript.

yes you heard it right Javascript is the most known and famous language on the planet according to StackOverflow, sorry if I crashed your python or c++ or PHP or java fantasies.

Here it is important to know that react-native apps are not browser-based like PhoneGap or Cordova. instead, these apps are written in javascript and rendered in native UI but still, the logic of the app is running in javascript. That means you have good performance but you have less than native performance. which is what we want for most apps. But here its good to note you have to choose frameworks according to its pros and cons according to your app you are building. If you want a very performant app its better to choose other frameworks like Flutter or native codes.

Your very first React Native App

setting up the development environment for React Naive might be a little bit of a hassle for some people. I suggest strictly following the docs at the Official react-native website

with that being said let’s go ahead and start our react native app

$ npx react-native init OurFirstAwesomeApp
//this will start the app template for you

With the code above react-native, CLI will give you the basic boilerplate for your app.

after that what you want to do is change the app.js to reflect your changes in your new app

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

function App() {
   return (<View>
           <Text> hello world from react-native </Text>
          </View>);
}

export default App;

As you can see from the above code, we have written a very similar code with react.js. in the above example the only difference being we have used View and Text instead of HTML tags.

As we have discussed before in React-native the UI is converted to Native UI, which is a great thing because it gives you the native speed and also enables you to give instant feedback.

React.js Let's Hook

Posted On 18 December 2019 ( 5.1 Minute Read )

React.js Let’s Hook

If you are a starter to react, I suggest that you read this blog first on how to get started with react.js.

When did Hooks come along?

Hooks are a new addition in React 16.8″ React.js official site. This means that to use Hooks, you need to have React.js version 16.8 or later.

But Hooks has brought some frustration among some react developers, They argue It’s inappropriate to bring Hooks in to play in a matured and well-understood library like react, But Most developers agree that Hooks can transform the react library itself and some of its limitations that the developer been facing so far. we will list some of the pros of using Hooks below and why we use Hooks here in Addis Software and why you should. We hope that other software developers in Addis Abeba shares our view

Hooks come in to play Because there were problems. Well, Hooks don’t solve all problems, but they still solve some of the problems we have faced with react development and making a complex application using merely components.

By the way, one thing to note here is that the react team is not planning on replacing class components by Hook out of a sudden, they have a strategy they call it “Gradual Adoption Strategy”. As you might have guessed classes are going to stay for a while.

Here are some of the problems with react class components and why they are being replaced by Hooks.

  • It’s hard to reuse stateful logic between components
  • Complex components become hard to understand
  • Classes confuse both people and machines
  • react more about motivations here

Play by the rules

If you are convinced by Hooks into play, let’s proceed to write hooks. But before that, we have to set some rules before we start the fun part. Here are the rules to write hooks

  • Always call hooks from the top-level ( don’t call in loops, iterative functions … )
  • Start with a Capital letter ( something that very similar to class components)
  • Don’t call hooks from regular javascript functions

now without any further ado, let’s Hook

in the code below, we will just print out some basic example to help us understand the basic components of a Hook, that is a react Hook

import React from 'react';

function OurFirstHook () {
   return (
        <div>
         <h1> our first Hook </h1>
        </div>
         )
}
export default OurFirstHook

But in the snippet above we didn’t use any Hook APIs so we are going to do that in the next example below

import React from 'react';
function OurFirstHook () {
const [clicked , setClicked] = React.useState(0);
const clickedHundler = (event) => {
     setClicked(clicked+1);
}
   return (
        <div>
         <Button onClick={clickedHundler}> 
{`button clicked ${clicked} times`}
 </Button>
        </div>
         )
}
export default OurFirstHook

We think that Hooks will be used more often by software developers in Addis Abeba and all over Africa.
we will discuss the code above line by line in the next Blog, til then ,

and also you can subscribe to our newsletter to get notified when new blogs come in

Loading

How to get started with react.js

Posted On 11 December 2019 ( 7.5 Minute Read )

HOW TO GET STARTED WITH REACT JS

What is react.js?


In this blog, we will discuss what Javascript is and What a library is and we will take a look at react The most famous Javascript Library in javascript.

JavaScript often abbreviated as JS, is a high-level, just in time compiled, object-oriented programming language that conforms to the ECMAScript specifications. according to Wikipedia. Javascript is very different from other programming languages like Java ( which inspired Javascript ) and c++ Because it runs in browsers.

But after a couple of attempts, javascript was hugely accepted as a server-side language starting from 2009 with the first release of node Js. This was a huge Game Changer for programmers who knew the language (working in browsers), Because now without learning a new language they can write server-side applications also.

This was not the only breakthrough we have seen with Javascript but also Javascript is used to work with mobile applications, Desktop applications, Tv applications and much more. Now it is true to say javascript can be used to build anything.

So as you might have guessed learning javascript is very important in the tech world right now. Not only that Javascript has a huge number of frameworks and libraries to get you rolling quickly and neatly. One of them being React.

React is a library for javascript that has the view layer in the famous MVC architecture. Before we dive into React, let’s discuss what a library is and the difference it has with a framework.

What is a Library


A library is a collection of resources ( in our case code ) written by someone to help roll quickly. The concept is pretty simple, Library is someone’s code to help you with a problem or issues that you can bring to your code to solve similar issues or problems. The code is reusable so you don’t have to write it on your own. for example, if you have worked with java, you know you have to import the String package to access the functions or resources in that package. library is the same, you reuse the code someone has written for a similar problem that you are facing.

SO, What is the difference with framework ?


well, A framework and library are similar things, they are codes written by someone that you bring to your project or code to solve similar issues. Well, what a library does is give you certain tools to deal with the problem at hand, well Framework seems to go beyond. Library gives you the furniture, Framework can build you the whole house.

well Technically speaking, if you are using a framework the framework also tells or influences the flow of your app, the design and also the architectures in some cases. But a library doesn’t force any flow on you. Instead gives you full control and will take care of little details you don’t have to bother about.

What is react.js


simply react.js is a javascript library that enables you to make your development and application fast and painless.

Things to dive in deeply when learning react.js

  • Virtual DOM
  • JSX
  • Context
  • State
  • Component
  • High-order components
  • Component Life cycles ( if you are learning react 5.9 or less )
  • Hooks

How to setup react


First install and setup Nodejs

React expects node js installed, install node js here node website

If you are using Linux make sure to install NPM separately.

Setup your first react project

run the following command

$ npx create-react-app my-app
// or if you have a template use
$ npx create-react-app my-app --template [template-name]
//then
$ cd my-app
//going into the project directory
$ npm start
//starting the application
//now you should see localhost:3000 loads your new app

you can now change your app.js in src directory with the code below

import React from react
function App() {
 return(
    <div>
     <h1> welcome to react.js </h1>
    </div>
     )
}
export default App

with that code, you officially are a React starter! ??

Where to go from here?

The first choice to learn to react would be the official react website here and also we would be writing about react here at addis software website. You can ask any question on the comment below.

How we use react.js in Addis Software

Here in Addis Software, We use React.js to build frontEnd web applications and also Cross-Platform Mobile Applications. Building a cross-platform Mobile application is very helpful, as it enables you to achieve the development speed and also gives you a native speed for your app.

Lifting our country out of poverty using Technology

Posted On 29 November 2019 ( 5.1 Minute Read )

Lifting our country out of poverty using Technology

Ethiopia’s Economy


Ethiopia is mentioned as one of the poorest countries on earth, the country name is mentioned as the highest poverty rate in the world in 2000 with 56 percent of the population living on less than the United States (U.S.) $1.25 purchasing power parity (PPP) a day, according to the world bank. This is a shocking fact since no country has this figure anywhere on this planet. But this figure has been decreased somehow from 200 to 2011. Even if the figures went down somehow, we all know the poverty rate in Ethiopia is very frustrating.

Progress


Now the country is making progress getting out of the situation where it used to be. The country has been trying to industrialize and create enough jobs for the youth that graduate every year from more than 34 universities and a ton of collages.

solutions


The progress is very slow. Even if we have to blame much of the problem on the education system, it’s very surprising to see Ethiopia going to bricks, while western countries have already shifted from bricks to clicks in the early 21s. This is one of the reasons why developing countries can’t achieve what developed countries are achieving. If the country is going back to bricks, sure the country is going to start on the clicks late, this would make the country, Technology importer rather than a fabricator. This, in turn, would get us to our loop, which is a loop that would always put you behind, and you would never compete with the rest of the world. It seems like we are running but we are on our second loop while the other has reached their forth.

It is very obvious that we need bricks before going to clicks because you can’t click if you have nothing to manage (the bricks), which means you are going to click your brick, not the other way round( not right now but this might happen in the future ). But if you wait to clicks till you get all your bricks. That would put you behind because people are already moving from clicks to other trends. But instead what is better is to build your bricks and clicks at the same time.

one of the biggest problems we have in developing countries is that we always seem to follow the developed nations, it feels like if they follow the developed countries one day they might have those names that they have developing. But the truth is different from the marathon, and it is following can’t let you lead. As we talked earlier following will only get you in the following loop, which will keep the ‘ing’s to the develop, as your name.

conclusion

As a developing country, we need to start influencing rather than following and that is why we need to catch on trends and start creating those. Catching on trending fast is not only to influence but also can help us leverage the potential we had and make an efficient way of using it.