Cannot read property setState of undefined

This will be a very quick guide for the above error.

This is common to have on the react using class or stateful component.

Take the following example


import React, {Component} from 'react';
class App extends Component {
    constructor() {
        super();
        this.state = {name: "default"};
    }

    keyHandler(event) {
        this.setState({name: event.target.value})
    }

    render() {
        return (
            
The name is {this.state.name}
<input id="name" onKeyUp={this.keyHandler} /≶
); } }

if you have something like the above one, where you haven’t bind the method to the class, then the error will happen.

Just adding

this.keyHandler = this.keyHandler.bind(this);

in the constructor will handle the issue.

longest word in the sentence

find longest word in the sentence

Find the longest word in the sentence

I am using javascript for this question.

It can be done in a lot of ways. The straight forward way could be the fastest probably. You will loop over the array of the words – you can split it with space – ” “.

Then just compare the value of the word length with maximum value and overwrite when it is higher – you know what I mean..

I will show the single liner for this though


var longestWord = "Guess what the longest word in the dictionary is".split(" ").sort(function(a, b){
    return b.length - a.length;
})[0];

Let’s go through what is going on..

The first part "Guess what the longest word in the dictionary is" is the given example sentence we are trying to find the longest word for.

Then we split the string into array of words using the split(" ") function. Now we have array to work with.

Then we sorted the array with sorter function passed to it. Sorter function in this one is anonymous function that we pass to it.

Finally we just took the first element of the sorted array which is sorted by the length of the word.

Also with the same concept, we have have it using reduce function;

"I still am having the wonderfulness of this thing ".split(" ").reduce((word1, word2) => word2.length > word1.length ? word2 : word1 );

That is it!

Flatten nested javascript array

How do you flatten array in javascript

If you are given an array that contains literals, arrays and objects and you want to get all the values to one array.

Here is the snippet using recursive function to attain that.


function implode(arr) {
	var res = [];
	for (var i =0; i < arr.length ; i++) {
    	if (Array.isArray(arr[i])) {
        	res = res.concat(implode(arr[i]));
		} else if(typeof arr[i] == 'object' ) {
			var values = Object.values(arr[i]);
        	for (var j = 0 ; j < values.length ; j++) {
            	if (!Array.isArray(values[j]) && typeof values[i] != 'object') {
					res.push(values[j]);
                }else{
                	res = res.concat(implode(values[j]));
				}
			}
		} else {
			res.push(arr[i]);
        }
	}
	return res;
} 

javascript queue and stack implementation

Implement Queue Using two Stacks – JavaScript algorithm

Using stack data structure to implement queue in javascript

This is one way of implementing of the stack to be reused as queue using two stacks.

You may complain you are abusing the memory. But we are not copying the data on both stacks we are using the stacks for switching values only


            class Queue {
                constructor() {
                    this.inputStack = [];
                    this.outputStack = [];
                }

                enqueue(item) {
                    this.inputStack.push(item);
                }

                dequeue(item) {
                    this.outputStack = [];
                    if (this.inputStack.length > 0) {
                        while (this.inputStack.length > 0) {
                            this.outputStack.push(this.inputStack.pop());
                        }
                    }
                    if (this.outputStack.length > 0) {
                        console.log(this.outputStack.pop());
                        this.inputStack = [];
                        while (this.outputStack.length > 0) {
                            this.inputStack.push(this.outputStack.pop());
                        }
                    }
                }

                listIn() {
                    let i=0;
                    while(i < this.inputStack.length) {
                        console.log(this.inputStack[i]);
                        i++;
                    }
                }
                listOut() {
                    let i=0;
                    while(i < this.outputStack.length) {
                        console.log(this.outputStack[i]);
                        i++;
                    }
                }
            }

*There is part left out for improvement and refactoring. But, can you see a way to use only one while rather than two whiles and make it a bit efficient?

Check if Function Exists in Javascript

How to check if function exists in javascript

Javascript might not be happy if you call function before it is being created. This can happen in a couple of cases.

You might be wondering how to check if function exists in javascript before calling it.

Lets say you have a onLoad logic, and there could be function definition below it. In that case, if you try to call the function from the onLoad, it might complain as

Uncaught referenceError: functionName is not defined 

This happens only because the browser will be creating the function later and there is no precedence on this.

How to fix Uncaught referenceError: is not defined javascript error

In this case you can check if the function exists first and call it afterwards:


if (typeof functionName == 'function') {
    functionName();
}

This will solve the problem. But there is a catch, you need to recall it again you make sure it is loaded.

Let me know if this solves your problem or not. I can add more based on your questions or suggestions.

how to get user input and process it in nodejs tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Now we have advanced a bit more and have served an html file from node js in this tutorial.

It would be a matter of updating the html file to have the user input box and adding one more route in node js to wait for specific url, getting the input and posting back the processed data.

In this part, the app will accept a name from the user and will print an email address containing the name that is provided.

How to get input from the user

If you have followed this tutorial, start from number 4

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input and add the following snippet in it.


 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     response.sendFile(__dirname+"/views/index.html");
 });
 
 app.get("/getemail", function (request, response){
     var firstname = request.query.firstname;
 
     if (firstname != "") {
         response.send("Your email address is " + firstname + "@gullele.com");
     } else {
         response.send("Please provide us first name");
     }
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

5. create a folder views in node-input folder

6. create index.html inside views and add the following code in it


<html>
    <head>
        <title>Simple hello world</title>
        <style>
            .prompt {
                font-size: 16px;
                color: brown;
                font-weight: bold;
                margin-bottom: 5px;
            }
            .container {
                width: 50%;
            }
            .left-pane {
                width: 50%;
                float: left;
            }
            .right-pane {
                width: 50%;
                float: right;
            }
            .submit-name {
                clear: both;
            }
        </style>
    </head>
<body>
    <h1>Hello Node JS</h1>

    <form method='GET' action="/getemail">
        <div class="container">
            <div class="prompt left-pane">
                <span>Give us your firstname and get email address</span>
            </div>
            <div class="right-pane">
                <input type="text" id="firstname" name="firstname" />
            </div>
        </div>
        <div class="submit-name">
            <input type="submit" value="get the email" />
        </div>
        </div>
    </form>
</body>
</html>

7. Save this file and start the sever using

node server.js

8. Now go to browser and surf http://localhost:8080

As you can see, the main point here would be adding one more route app.get("/getemail", function (request, response){ and accessing the parameters using the request object then passing the response with processed name in it.

The next would be to see how node can accomplish rendering the next page with values. And for that, there is a need to have template engine introduced.

Next: Using template engine ejs with node js

how to display html files from node js example tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Here We have see how to print a Hello World for a request of “/”. That is a good advancement but that won’t give us much to proceed. We need a way to server html files for different requests.

So, what we want to do is to have more flexibility by having html file. We will have all the contents as we wish using the old school html tag and we will serve that through node js.

Displaying and rendering html file through node js

If you have followed this then start from number 4

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input.


 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     //show this file when the "/" is requested
     response.sendFile(__dirname+"/views/index.html");
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

5. create a folder views in node-input folder

6. create index.html inside views and add the following code in it


 <html>
 <head><title>Simple hello world</title></head>
 <body>
 <h1>Hello Node JS</h1>
 </body>
 </html>

7. go to your browser and type http://localhost:8080

You will see Hello Node Js on the browser big and bold.

What is going on

It is like the previous example except we are serving the actual physical html file this time.

By doing so, we have more control on the html file like adding css and javascript codes or calling those files on the page.

Mind you, index.html is the entry point, once we got on that page, we can navigate to other pages and do more

**If the above app is not working for whatever reason, make sure to update npm and get newest version

npm i -g npm-check-updates
npm-check-updates -u
npm insert

Next: Accepting input from the user and processing it.

a hello world tutorial using node js with http web server

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

In order to have simple website that is displaying hello world, we need to have a web server. In the previous example there was no need to have a web server since the message was shown from command line.

Node provides its own web server that we can serve http request and responses.

I will cover on the later tutorial how those would be used, for now. All we need is to be able to go to http://localhost:8080 and see the the output of hello world

Serving the page through web server

If you have followed the above tutorial listed on the link, start from number 3.

1. Create a folder in your computer and name it as node-tutorial

2. In the node-tutorial folder create server.js file

3. On server.js add the following code in it and save it.


 var http = require("http");
 var server = http.createServer(function (request, response) {
 response.writeHead(200, {"Content-Type":"text/plain"});
 response.end("Hello World");
 });
 
 server.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

4. go to your browser and type http://localhost:8080 and you will see Hello World being printed on your browser.

Congratulations! you have successfully created a website that prints Hello World.

What is going on

The above snippet creates a very basic yet full fledged web server. At the heart of any web server are request and response

request is what the browser behalf of the user is sending to the server and it waits for the server to give it back something to show to the user. The request is the one that contains the form elements usually

response is what the server would be responding based on the request forwarded to the server. It contains usually the type of the response data, like text or json or image through its header and the actual data to be returned.

require("http"); This part tells node to import the http package for usage.

With the hello world example above, the request contains no input fields but it is full request in that it is requesting for the response of hello world.

Don’t worry if you don’t get much of the request response stuff, as it would be clear on the upcoming parts of this tutorial.

Since simply printing Hello Worlds is not that much fun. We will see how to do some other exciting stuffs on the upcoming parts of tutorials.

Next: Accept input from the browser/user and process the input

node js mongo db and angular js tutorial for beginners from scratch

node js beginner guide with mongo and angular

node js step by step tutorial showing you how to create a full fledged node js angular js and mongo db for beginners who have never played with these technologies or played partially independently but not all those technologies together.

I assume installing nodejs to your computer can be found easily and I will not go through that.

Starting with a simple Hello world display with webserver

Node js is a fully functional webserver and processor that is created off of Googles V8 engine. It is very light weight and the syntax is javascript syntax.

Unlike other languages where you have to setup and configure a different independent webserver, node js, comes with a total self contained web server serving at ports that you can assign. Which makes it a full one stop web application.

For comparison, when working on php might require you to setup a different webserver like Apache or IIS.

In this part, I will show a very simple old school hello world example to be done in node js.

In the upcoming tutorials, you will see how to change those step by step.

Hello world in node js

1. Create a folder in your computer and name it as node-tutorial

2. in the node-tutorial folder create hello.js file

3 on hello.js add the following code in it.

console.log("Hello World");

Then save the above file and run the file as

node hello.js

This will print Hello World in the CONSOLE.

What did happen

The above code is running from the node js as a command line code. There is no any web server, that making it available through browsers per se, this time, it will just print that on right on the terminal you are running it.

You might know console.log() from your javascript coding and it is doing the same task here in node as well.

Next: Run Hello World using http through browser