JavaScript, React

ES2017 async/await with fetch in Redux (No Callback Hell anymore)

When we need to use third party API or any REST API in our web app, we need to wait for the response coming from the server.
Then in the success callback , we use that data and do other operations.And if we have more REST calls, we all know that it could end up being a Callback Hell

But if we use ES2017 async/await syntax , we can write our code as clean as possible with minimum lines of code.

Basic example of async/await is like below-

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

here var result = await resolveAfter2Seconds(); will wait to resolve the Promise and assign the returned data to `result` variable.
It seems like its executing the code line by line though it has asynchronous operation , which is awesome!

As of now , we know basic of async/wait , now we will use this inside redux ActionCreator. But first we will see how the code looks like without using async/await.
So our action creator code is –

export const getSpeakers = () => (dispatch, getState) => {
  return fetch(`${API_SERVER}/speakers`)
    .then(
      response => response.json(),
      error => {
        console.log("No! error occured.", error);
        throw error;
      }
    )
    .then(speakers => {
      console.log("speakers success", speakers);
      dispatch(saveSpeakers(speakers));
    })
    .catch(error => {
      console.log("Return Error by throwing", error);
      throw error;
    });
};

So here ^ is our action creator named `getSpeakers` which calls one REST API endpoint and then dispatch the speakers to the redux store.Here we can see we need to chain with `then`, `catch` etc which make the code a bit messy and hard to understand.

Now we will use async/await with fetch and will make our code good looking

export const getSpeakers = () => async (dispatch, getState) => {
  try {
    const response = await fetch(`${API_SERVER}/speakers`);
    const speakers = await response.json();
    console.log("speakers success", speakers);
    dispatch(saveSpeakers(speakers));
  } catch (error) {
    console.log("throwing Error", error);
    throw error;
  }
};

Here , we have added try/catch so that if any error happens, we can catch and take our decision what we want to do. Here in this case , I have just thrown the error, but we can dispatch another FAILURE action.
Ah , that made our code smaller,cleaner and easy to understand!

Cheers!

Standard
React

Single Page Application (SPA) with React

Let’s talk about ReactJS today and how we can easily create a Single Page Application (SPA) with React. For routing , I will use a library called react-router . For this post, I will use v3.x . I will write another article based on v4.x.

ReactJS is really popular now a days , and developers are using ReactJS and react-router for creating SPAs .

react spa

I will use 4 Routes for my sample SPA with React. For this , I created 4 Components which represent 4 different routes.
Then we can import 4 Components on index.js file like below-

import App from './App/Components/App.jsx';
import Profile from './App/Components/Profile.jsx';
import Contact from './App/Components/Contact.jsx';
import Error from './App/Components/404.jsx';

Our `404.jsx` is actually for 404 or not found route.

We can use those Components to create out SPA routing with react-router-

<Router history={hashHistory}>
    <Route path="/" component={App}>
        <Route path="/profile" component={Profile}/>
        <Route path="/contact" component={Contact}/>
        <Route path="*" component={Error}/>
    </Route>
  </Router>

The full Code is available here https://github.com/destromas1/react-spa

Cheers!

Standard
JavaScript, React

Play with React for beginners with react-basic-starter

I have been working with React for long time now . But as I was not regular in writing , that’s why I have never written a single post on React.

This would be officially my first ReactJS post , and I know I am late.

react-basic-starter

Its 2017 . There are lot of articles published on Web . Facebook has created a tool for React developers called create-react-app which is awesome for starting any new react based project. But What I feel , if anyone is a fresher in React , then its a bit more than the skill level.Also I feel React Developers should learn a bit of Webpack , thats why I added a simple Webpack Config for building react code.

This post actually tries to help a react fresher to start creating his/her first React sample component and do some fun in his Bedroom playground.

module.exports = {
  entry: './index.js',
  output: { path: __dirname, filename: 'bundle.js' },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {

        }
      }
    ]
  },
};

The upper code snippet is available inside webpack.config.js file and It will build the React Code and JSX and create a file called `bundle.js`

Inside our `index.html` file we have included this bundle to load as script.

<script src="bundle.js"></script>

Our simple component is available on `App.jsx` file which has only one H1 inside.

export default class App extends React.Component {
  render() {
    return(
      <div>
        <h1>React Basic Starter</h1>
      </div>
    )
  }
};

Full code is available at my Github Repo https://github.com/destromas1/react-basic-starter

Cheers!

Standard
.Net Core, ASP.Net

.Net Core – New Taste from Old School

After working few years with .Net , I started working with NodeJS Stack as Full Stack JavaScript is really awesome and isomorphic era attracted me a lot . I have worked with AngularJS , ReactJS , Electron and a lot of popular JavaScript Frameworks / libraries at frontend and backend.

After Mr. Satya started working as CEO , he has been doing a lot of changes. Making .Net open source was really a big move for MS.

Microsoft introduced .Net Core . And the concept of this seems similar(Conceptually) to NodeJS .

They removed old packages.config file and introduced project.json which is fully conceptually similar to NPM’s package.json , even the Keyword is similar “dependencies” , “scripts” etc .

They removed ASP.Net Forms , which is surely a good thing.

One of the cool things is that , Microsoft understood that Its high time to make .Net CrossPlatform , otherwise they would have lost the developers community as people moving to NodeJS , GO , and Functional programming stuffs who use Linux and/or MAC . Coz .Net was only for Windows users before. But now .Net core can be run in any platform which is awesome and definitely a good business trick for Microsoft.

Today , we will see how we can run .Net core in Ubuntu.

I am using Ubuntu 16.04

sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main" > /etc/apt/sources.list.d/dotnetdev.list'

sudo apt-key adv --keyserver apt-mo.trafficmanager.net --recv-keys 417A0893

sudo apt-get update

sudo apt-get install dotnet-dev-1.0.0-preview2-003131

To verify run

dotnet -v

Always have an eye on this Page for Installing Updates .net-core-ubuntu

Standard
System

Node app Deployment and development process Manager

For development , its better to use nodemon

To install

npm install -g nodemon

To run

nodemon server.js

 

For Production , For most cases we can use forever

To Install

[sudo] npm install forever -g

To run

forever start app.js

forever start -a server.js

forever stop server.js

forever list

To see continuous Logs in terminal

forever logs server.js -f

Standard
NodeJS

Upgrade your Server to NodeJS LTS Version from old versions

If you have NodeJS already installed , then first remove the current installation.

sudo apt-get remove --purge nodejs npm

Now lets install NodeJS LTS 4.4.0 Argon –
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs

You might need to link to node
sudo ln /usr/bin/nodejs /usr/bin/node

Verify
node -v
node -pe process.release.lts

Standard
C#, Cross Domain, HTML5, JavaScript, NodeJS

Visual Studio Code – A Cross Platform Code Editor built with Chromium

Microsoft has launched VSCode few weeks back for Cross Platform (Linux/Mac,Windows) and 55% download was Non-Windows. Shocking , right ?

HackerNews had a post on this and had really lot of comments/traffic on it.

Lets see the first look of Code.

Code First Look

Code First Look

Its lightweight and simple and has GIT embedded with this.

But I am not here to say that Code has been released by Microsoft. I am here to shock you little bit.

When you are on Code, Just press F12.

And lets see the below image.

Code First Look Shocked

Code First Look Shocked

#%$#@ ???? Is it Chrome Dev Tools ?

YES !!! It is!

In fact VSCode has been built with Web Technologies like HTML,CSS , JavaScript with Chromium and NodeJS . Here , Chromium is the Engine for Chrome browser by Google.

Lets get a little idea about CEF (Chromium Embedded Framework)

Tech

And they used Electron for Cross Platform . Electron helps to Build cross platform desktop apps with web technologies Formerly known as Atom Shell. Made with Love by GitHub.

Initially developed For GitHub’s Atom editor , Electron has since been used to create applications by companies like Microsoft, Facebook, Slack, and Docker.

Slack‘s new Desktop app was also built with this.

In VSCode , what we do Like adding/editing Projects/Folders/Files , all is saved in HTML5’s Client Side DBs like IndexedDB and LocalStorage. To know more about HTML5 Database , you can see my other posts on HTML5 Database here
https://shahjadatalukdar.wordpress.com/2013/09/27/using-html5-localstorage-with-angularjs/

https://shahjadatalukdar.wordpress.com/2014/01/18/websql-welcome-to-client-side-db-part1/

Lets see the below image.

HTML5 Database

HTML5 Database

Okay , lets see Where the World goes to!

Cheers!

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

Standard
AngularJS

MEAN.io – Installing in Windows 8.1 (MEAN Stack)

MEAN.io is becoming a Popular Modern Framework for MEAN Stack(Mongo , Express , Angular , Node). I have recently tried it out and had real fun with it , such an awesome Boilerplate for MEAN Stack.

banner-top-ninja

Most of the Developers around the world work on MAC/LINUX when they are with MEAN. But I thought why not to write a Full Process for Windows Users . Cool , lets do the whole thing to get running an MEAN.io app in Win8.1.

First , We need to install the Core Node And Mongo.

1.Lets install Node first.Go to Node Download Center and Download Windows Installer (.msi) based on your OS Architecture and just Install with few Clicks.

2.Lets Install MongoDB , to see How to Install Click Here

3.Some of Mean.io dependencies uses node-gyp with supported Python version 2.7.3.

3.1.Install Python From here

Python

Python

3.2. Install Microsoft Visual Studio C++ 2012/13 for Windows Desktop (Express version works well)

3.3.Install node-gyp

npm install -g node-gyp

4. Install Gulp and Bower

npm install -g gulp

npm install -g bower

5.Install the MEAN.io CLI

npm install -g mean-cli

6.Now create your own app

mean init myApp

cd myApp
npm install

7.To start you application run –

gulp

Alternatively, when not using gulp (and for production environments)

node server.js

And browse http://localhost:3000

You can see your Site , All done by the amazing Mean.io

Mean

Mean

Standard