Sunday, February 7, 2021

State management in React Native Part-2

Context can only store a single value, not an indefinite set of values each with its own consumers. 

In order to solve this problem, we needed a way to provide a global state that all components, regardless of how deeply nested they are, could access. React Hooks and Redux are ways to manage state in a React app.

In Previous blog we've got mentioned about Context API, now will see in information about the Redux.

Redux:

The Redux describes it as a predictable state container for JavaScript applications that helps us to write programs that behave constantly, run in several depths and widths of elements, and are easy to check.

Redux is a state control library used to store and manage the state of a react software in a centralized position. Redux abstracts all states from the app into one globalized state object in order that any component and any a part of the app can get access to the different properties of the global state. Redux is separate from React and there are libraries to combine Redux into React apps.

Friday, February 5, 2021

State management in React Native Part-1

It is best to use React's built-in state management capabilities rather than external global state for smaller Apps, but default React state has certain limitations: Component state can only be shared by pushing it up to the common ancestor, but this might include a huge tree that then needs to re-render.

Context api with React Hooks

The React Context API is React’s approach of managing state in more than one elements that are not directly connected. You can create your individual custom hooks to avoid repetition and make code cleaner. Context supplies a way to pass data in the course of the component tree without having to pass props down manually at every level. Custom hooks are customary JavaScript functions which is able to use different React hooks.

Without Hooks, the Context API may no longer seem like much when compared to Redux, however mixed with the useReducer Hook, we have now an answer that finally solves the state management drawback.
Custom hooks resolve the problem of fending off repetition and make code cleaner. Context supplies a strategy to move information in the course of the component tree with no need to go props down manually at each and every stage.

Thursday, December 13, 2018

Search keywords in HTML content and highlight


Declare below variables in class
highlightClass = "highlightText";
highlightRe: any;
spaceRe = /\s+/;
spaceRe2 = /\s+$/;
before: any = "";
after: any = "";

Thursday, November 22, 2018

Call a function of Controller "One" inside Controller "Two" - IONIC1

app.controller('One', ['$scope', '$rootScope'
    function($scope) {
        $rootScope.$on("CallParentMethod", function(){
           $scope.parentmethod();
        });

        $scope.parentmethod = function() {
            // task
        }
    }
]);
app.controller('two', ['$scope', '$rootScope'
    function($scope) {
        $scope.childmethod = function() {
            $rootScope.$emit("CallParentMethod", {});
        }
    }
]);

While $rootScope.$emit is called, you can send any data as second parameter.

Solution for IONIC2+  will be up soon.

Whatsapp message from hybrid app


There are two different ways to open whatsapp form hybrid application.

<a target="_blank" href="whatsapp://send?text=hello">open whatsapp</a>



<a target="_blank" href="whatsapp://send?text=my message&phone=+XXXXXXXXXXXX&abid=+XXXXXXXXXXXX">Whatsapp me please</a>


Monday, July 24, 2017

Log execution time of function/Ajax Call



Initialization of the variable to store all logs in controller

$rootScope.timeSlots = {};



//Function to create object with eventname , start time, end time using ID
$scope.logEvent = function(Eventid, EventName, isEnd){
    if(isEnd == false){
         $rootScope.timeSlots[Eventid] = {
            "name": EventName,
            "startDate":new Date().getTime()
         };
    } else {
        $rootScope.timeSlots[Eventid]["endDate"] = new Date().getTime();
    }
};
Log starting time 
$scope.logEvent("function1","Function1 start Time", false);

Tuesday, June 20, 2017

Angular/Ionic not updating an image src when ng-src is empty

The Angular ngSrc directive serves to properly set an image src via Angular. As anything in Angular, it updates the image as soon as the contained Angular expression changes. However, when the ng-src attribute is empty, Angular will not empty the src attribute. To overcome this, use the trick below.
<img ng-src="{{ element.image || '//:0' }}" />

Background

The ngSrc directive explicitly returns when the attribute value is false. As a workaround, set a "blank" image src when the image is empty. As somebody on Stackoverflow writes, //:0 serves this purpose: It adopts the current protocol, omits the hostname and sets the port to zero, which is invalid and should be killed by the network layer.
As a result, Angular should now correctly empty the src attribute when ng-src empties.


Change timeout for connection request in iOS

Code to change ajax request timeout for ios and also for hybrid(Cordova) apps.

Find NSURLRequest in your native code. Change the timeoutInterval value.

  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serverURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];



👍

Wednesday, February 15, 2017

Multiplication of two numbers as array - In Javascript

Javascript Code 

var arry1 = [3,4,6,9,9,9];
var arry2 = [9,8,9,8,5];
$("#arry1").html(arry1.toString());
$("#arry2").html(arry2.toString());
var directResult = arry1.join('') * arry2.join(''); // to compare result 
$("#result").html(directResult);
var calResult = [];
var vadi=0;
for(var i=0;i<arry2.length;i++){
  calResult[i]=[];
  vadi = 0;
  for(var j=arry1.length-1;j>=0;j--){
    var temp= arry1[j]*arry2[i]+vadi;
    if(temp.toString().length > 1){
      vadi = parseInt(temp.toString().substr(0, 1));
      temp = parseInt(temp.toString().substr(1, 1));
    } else{
      vadi = 0;
    }
    calResult[i].unshift(temp);
  }
  for(var k=i+1;k<arry2.length;k++){
      calResult[i].push(0);
  }
  if(vadi!=0){
    calResult[i].unshift(vadi);
    vadi = 0;
  }
  if(calResult[i].length != calResult[0].length){
    var lengthDiff = calResult[0].length-calResult[i].length;
    for(var p=0;p<lengthDiff;p++){
      calResult[i].unshift(vadi);  
    }
  }
}
var finalResult = [];
var finalvadi = 0;
for(var m =calResult[0].length-1;m>=0;m--){
  var tempr = 0;
  for(var n=0; n<calResult.length;n++){
    tempr+=calResult[n][m];
  }
  tempr+=finalvadi;
  finalvadi=0;
  if(tempr.toString().length > 1){
    finalvadi = parseInt(tempr.toString().substr(0, 1));
    tempr = parseInt(tempr.toString().substr(1, 1));
  } else{
    finalvadi = 0;
  }
 finalResult.unshift(tempr);
}
if(finalvadi!=0){
    finalResult.unshift(finalvadi);
}
$("#finalResult").html(finalResult.toString());

HTML Code

 <div id="arry1"></div>
<div id="arry2"></div>
<div>-----------</div>
<div id="result"></div>
<br/><br/>
<div>------------------</div>
<div id="finalResult" style=""></div>


Output: 


3,4,6,9,9,9
9,8,9,8,5
-----------
34347696015


------------------
3,4,3,4,7,6,9,6,0,1,5

Tuesday, September 6, 2016

IONIC - data binding on header title not working

By using the new ion-nav-title directive in Ionic beta 14, the binding seems to work correctly.
Rather than
<ion-view title="{{content.title}}">

Do this
<ion-view> <ion-nav-title>{{content.title}}</ion-nav-title>

Works a treat.

Monday, August 8, 2016

Self Signed SSL Certificates in PhoneGap

Code to allow self signed certs on PhoneGap 

Android:

  • If you are doing development: android:debuggable="true" in the manifest, you should allow the browser to request data from servers with a self-signed or bad SSL cert 
  • If you are releasing an application, you should remove the android:debuggable="true" (Android Market won't let you release with this on anyway) and you will NOT be able to send data to a server with a bad SSL cert 
  • If you don't have this flag set, the default will be what the default is now, which is that you won't be able to send data to servers with a self-signed cert 

iOS: 

Just Add below code at the end of you AppDelegate.m file
@implementation NSURLRequest(DataController)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES; 
}
@end

Thursday, June 9, 2016

Error: Database location or iosDatabaseLocation value is now mandatory in openDatabase call

if you are using Cordova sqlite plugin you may have this issue while open local DB file.

 _sqlLiteDB = $cordovaSQLite.openDB({ name: "testDB.db", iosDatabaseLocation:'default'}); 
// Works on android but not in iOS

                   

Error: Database location or iosDatabaseLocation value is now mandatory in openDatabase call



Use below to open DB:
window.sqlitePlugin.openDatabase({ name: "testDB.db", location: 2, createFromLocation: 1});


Solution:

if(isAndroid){
                    // Works on android but not in iOS
                    _sqlLiteDB = $cordovaSQLite.openDB({ name: "testDB.db", iosDatabaseLocation:'default'}); 
} else{
                    // Works on iOS 
                    _sqlLiteDB = window.sqlitePlugin.openDatabase({ name: "testDB.db", location: 2, createFromLocation: 1}); 
 }



Friday, June 3, 2016

Warning: sqlite3.c Ambiguous expansion of macro - Xcode - iOS

Plugin: cordova-sqlite-storage

Version: 1.4.1

Warning: sqlite3.c Ambiguous expansion of macro - Xcode - iOS

This issue also helps on native app code. 


Issue Solution:

Open Xcode project Build settings


add “-Wno-ambiguous-macro” into  “Other C flags” 



Wednesday, June 1, 2016

error JSON.stringify()ing argument: RangeError: Invalid Date

There is minor bug in contact plugin in cordova ionic. contact list is loaded with error due to the birthdate field in contact card. Its bad practice to keep minor error in execution of code, It may effect to different OS versions.

error JSON.stringify()ing argument: RangeError: Invalid Date


Cordova Plugin: cordova-plugin-contacts
Verison: 2.1.0 "Contacts"


Open convertUtils.js file  

File Path: plugins/cordova-plugin-contacts/www/convertUtils.js



Find function "toCordovaFormat" and remove below try-catch code.


 try {
         contact.birthday = new Date(parseFloat(value));
} catch (exception){
          console.log("Cordova Contact toCordovaFormat error: exception creating date.");
}

add below code instead of try-catch

if (value !== null) {
        try {
                contact.birthday = new Date(parseFloat(value));
               
                //we might get 'Invalid Date' which does not throw an error
                //and is an instance of Date.
                if (isNaN(contact.birthday.getTime())) {
                       contact.birthday = null;
               }
               
        } catch (exception){
                console.log("Cordova Contact toCordovaFormat error: exception creating date.");
        }
}

Check below screenshot for better understand.




iOS contact card does not have value for "displayName". "displayName" is used for the android devices. So For iOS device, use "name.formatted" instead of "displayName".

Cheers.... Keep Coding... :)








Monday, May 30, 2016

Check the element is child of specific class element.

Some time we have the child element name, and want to check the element is inside the particular class or outside the class.

Please find below code to Check the element is child of specific class element.


<script type="text/javascript">function isChildOf(ChildObject,ContainerObject)
            {
                var retval=false;
                var curobj;
                if(typeof(ContainerObject)=="string")
                {
                    ContainerObject=document.getElementById(ContainerObject);
                }
                if(typeof(ChildObject)=="string")
                {
                    ChildObject=document.getElementById(ChildObject);
                }
                curobj=ChildObject.parentNode;
               // console.log(curobj.className+' '+ContainerObject.className);
               if(curobj==undefined) {
                return retval;
               }
                while(curobj!=undefined)
                {
                    if(curobj==document.body)
                    {
                        retval=false;
                        break;
                    }
                    if(curobj.className==ContainerObject.className)
                    {
                        retval =true;
                        break;
                    }
                    curobj=curobj.parentNode; //move up the hierarchy
                }
                return retval;
            }



var isChild = '';
         var child_Element = document.getElementsByClassName('childDIV');
                var tablinks = document.getElementsByClassName('parentDIV');
                for (var i = 0, j = tablinks.length; i < j; i++) {
                    var isChild = false;
                    //console.log(isChildOf(a[g],tablinks[i]));
                    if(isChildOf(child_Element,tablinks[i]) == true){
                        isChild = true;
                        break;
                    }
                }

 if(isChild == true){
        // YES child Element is in parent Element.
}

</script>

Cheers..:)

Friday, May 27, 2016

Keyboard Shortcuts (Microsoft Windows)

All keyboard shortcuts of windows microsofts. No need to use mouse every time for the small stuff. You can quickly do things using keyboard shortcuts. 

Keyboard Shortcuts (Microsoft Windows)


1. CTRL+C (Copy)
2. CTRL+X (Cut)
3. CTRL+V (Paste)
4. CTRL+Z (Undo)
5. DELETE (Delete)
6. SHIFT+DELETE (Delete the selected item permanently without placing the item in the Recycle Bin)
7. CTRL while dragging an item (Copy the selected item)
8. CTRL+SHIFT while dragging an item (Create a shortcut to the selected item)
9. F2 key (Rename the selected item)
10. CTRL+RIGHT ARROW (Move the insertion point to the beginning of the next word)
11. CTRL+LEFT ARROW (Move the insertion point to the beginning of the previous word)
12. CTRL+DOWN ARROW (Move the insertion point to the beginning of the next paragraph)
13. CTRL+UP ARROW (Move the insertion point to the beginning of the previous paragraph)
14. CTRL+SHIFT with any of the arrow keys (Highlight a block of text)
SHIFT with any of the arrow keys (Select more than one item in a window or on the desktop, or select text in a document)
15. CTRL+A (Select all)
16. F3 key (Search for a file or a folder)
17. ALT+ENTER (View the properties for the selected item)
18. ALT+F4 (Close the active item, or quit the active program)
19. ALT+ENTER (Display the properties of the selected object)
20. ALT+SPACEBAR (Open the shortcut menu for the active window)
21. CTRL+F4 (Close the active document in programs that enable you to have multiple documents opensimultaneously)
22. ALT+TAB (Switch between the open items)
23. ALT+ESC (Cycle through items in the order that they had been opened)
24. F6 key (Cycle through the screen elements in a window or on the desktop)
25. F4 key (Display the Address bar list in My Computer or Windows Explorer)
26. SHIFT+F10 (Display the shortcut menu for the selected item)
27. ALT+SPACEBAR (Display the System menu for the active window)
28. CTRL+ESC (Display the Start menu)
29. ALT+Underlined letter in a menu name (Display the corresponding menu) Underlined letter in a command name on an open menu (Perform the corresponding command)
30. F10 key (Activate the menu bar in the active program)
31. RIGHT ARROW (Open the next menu to the right, or open a submenu)
32. LEFT ARROW (Open the next menu to the left, or close a submenu)
33. F5 key (Update the active window)
34. BACKSPACE (View the folder onelevel up in My Computer or Windows Explorer)
35. ESC (Cancel the current task)
36. SHIFT when you insert a CD-ROMinto the CD-ROM drive (Prevent the CD-ROM from automatically playing)


Dialog Box - Keyboard Shortcuts


1. CTRL+TAB (Move forward through the tabs)
2. CTRL+SHIFT+TAB (Move backward through the tabs)
3. TAB (Move forward through the options)
4. SHIFT+TAB (Move backward through the options)
5. ALT+Underlined letter (Perform the corresponding command or select the corresponding option)
6. ENTER (Perform the command for the active option or button)
7. SPACEBAR (Select or clear the check box if the active option is a check box)
8. Arrow keys (Select a button if the active option is a group of option buttons)
9. F1 key (Display Help)
10. F4 key (Display the items in the active list)
11. BACKSPACE (Open a folder one level up if a folder is selected in the Save As or Open dialog box)


Microsoft Natural Keyboard Shortcuts


1. Windows Logo (Display or hide the Start menu)
2. Windows Logo+BREAK (Display the System Properties dialog box)
3. Windows Logo+D (Display the desktop)
4. Windows Logo+M (Minimize all of the windows)
5. Windows Logo+SHIFT+M (Restorethe minimized windows)
6. Windows Logo+E (Open My Computer)
7. Windows Logo+F (Search for a file or a folder)
8. CTRL+Windows Logo+F (Search for computers)
9. Windows Logo+F1 (Display Windows Help)
10. Windows Logo+ L (Lock the keyboard)
11. Windows Logo+R (Open the Run dialog box)
12. Windows Logo+U (Open Utility Manager)
13. Accessibility Keyboard Shortcuts
14. Right SHIFT for eight seconds (Switch FilterKeys either on or off)
15. Left ALT+left SHIFT+PRINT SCREEN (Switch High Contrast either on or off)
16. Left ALT+left SHIFT+NUM LOCK (Switch the MouseKeys either on or off)
17. SHIFT five times (Switch the StickyKeys either on or off)
18. NUM LOCK for five seconds (Switch the ToggleKeys either on or off)
19. Windows Logo +U (Open Utility Manager)
20. Windows Explorer Keyboard Shortcuts
21. END (Display the bottom of the active window)
22. HOME (Display the top of the active window)
23. NUM LOCK+Asterisk sign (*) (Display all of the subfolders that are under the selected folder)
24. NUM LOCK+Plus sign (+) (Display the contents of the selected folder)
25. NUM LOCK+Minus sign (-) (Collapse the selected folder)
26. LEFT ARROW (Collapse the current selection if it is expanded, or select the parent folder)
27. RIGHT ARROW (Display the current selection if it is collapsed, or select the first subfolder)


Shortcut Keys for Character Map


After you double-click a character on the grid of characters, you can move through the grid by using the keyboard shortcuts:

1. RIGHT ARROW (Move to the rightor to the beginning of the next line)
2. LEFT ARROW (Move to the left orto the end of the previous line)
3. UP ARROW (Move up one row)
4. DOWN ARROW (Move down one row)
5. PAGE UP (Move up one screen at a time)
6. PAGE DOWN (Move down one screen at a time)
7. HOME (Move to the beginning of the line)
8. END (Move to the end of the line)
9. CTRL+HOME (Move to the first character)
10. CTRL+END (Move to the last character)
11. SPACEBAR (Switch between Enlarged and Normal mode when a character is selected)


Microsoft Management Console (MMC)

Main Window Keyboard Shortcuts

1. CTRL+O (Open a saved console)
2. CTRL+N (Open a new console)
3. CTRL+S (Save the open console)
4. CTRL+M (Add or remove a console item)
5. CTRL+W (Open a new window)
6. F5 key (Update the content of all console windows)
7. ALT+SPACEBAR (Display the MMC window menu)
8. ALT+F4 (Close the console)
9. ALT+A (Display the Action menu)
10. ALT+V (Display the View menu)
11. ALT+F (Display the File menu)
12. ALT+O (Display the Favorites menu)


MMC Console Window Keyboard Shortcuts


1. CTRL+P (Print the current page or active pane)
2. ALT+Minus sign (-) (Display the window menu for the active console window)
3. SHIFT+F10 (Display the Action shortcut menu for the selected item)
4. F1 key (Open the Help topic, if any, for the selected item)
5. F5 key (Update the content of all console windows)
6. CTRL+F10 (Maximize the active console window)
7. CTRL+F5 (Restore the active console window)
8. ALT+ENTER (Display the Properties dialog box, if any, for theselected item)
9. F2 key (Rename the selected item)
10. CTRL+F4 (Close the active console window. When a console has only one console window, this shortcut closes the console)


Remote Desktop Connection Navigation


1. CTRL+ALT+END (Open the Microsoft Windows NT Security dialog box)
2. ALT+PAGE UP (Switch between programs from left to right)
3. ALT+PAGE DOWN (Switch between programs from right to left)
4. ALT+INSERT (Cycle through the programs in most recently used order)
5. ALT+HOME (Display the Start menu)
6. CTRL+ALT+BREAK (Switch the client computer between a window and a full screen)
7. ALT+DELETE (Display the Windows menu)
8. CTRL+ALT+Minus sign (-) (Place a snapshot of the active window in the client on the Terminal server clipboard and provide the same functionality as pressing PRINT SCREEN on a local computer.)
9. CTRL+ALT+Plus sign (+) (Place asnapshot of the entire client window area on the Terminal server clipboardand provide the same functionality aspressing ALT+PRINT SCREEN on a local computer.)


Microsoft Internet Explorer Keyboard Shortcuts


1. CTRL+B (Open the Organize Favorites dialog box)
2. CTRL+E (Open the Search bar)
3. CTRL+F (Start the Find utility)
4. CTRL+H (Open the History bar)
5. CTRL+I (Open the Favorites bar)
6. CTRL+L (Open the Open dialog box)
7. CTRL+N (Start another instance of the browser with the same Web address)
8. CTRL+O (Open the Open dialog box,the same as CTRL+L)
9. CTRL+P (Open the Print dialog box)
10. CTRL+R (Update the current Web page)
11. CTRL+W (Close the current window)


Enjoy.. :)

Wednesday, May 25, 2016

Easily Track Javascript File and line number which has error

When all else fails, the issue may be caused by errors in your JavaScript application. A helpful way to determine this is to use the window.onerror function to track down your errors.

Easily Track Javascript File and line number which has error


window.onerror = function (err, fileName, lineNumber) {
   // alert or console.log a message
   alert(fileName, 'Line:', lineNumber, 'Error:', e.message);
};

Parameter info: 
// err: error message
// fileName: which file error occurs in
// lineNumber: what line error occurs on

Monday, May 25, 2015

Top 5 Tutorial for Angularjs with PhoneGap



Hello folks!!

AngularJS is an awesome Javascript framework that can be used to create powerful and dynamic web apps. It also covers the building of complex client-side applications. I share very useful examples tutorial link for AngularJS with PhoneGap App building

Thursday, February 12, 2015

Smooth Scroll Using jQuery

Smooth Scroll Using jQuery Code:


$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Monday, September 29, 2014

Woocommerce issue when products and categories has same base path

404 on Product detail page?

Ran into this issue where I needed a url structure such as/shop/<category> and /shop/<category>/<product>/.

/shop/<category>/ works fine but once you click a product you get a nice looking 404 page.

My settings:
Product category base - /shop
Product permalink base -> Custom Structure - /shop/%product_cat%

The Fix:

Set the ‘Product category base’ to shop and the custom product base to /shop/%product_cat%.
Then in your functions.php file add this little snippet: