ReactJS/Redux Exception – Uncaught TypeError: Cannot read property ‘type’ of undefined

ReactJS/Redux Exception – Uncaught TypeError: Cannot read property ‘type’ of undefined

This issue might occur in many cases but one case which is hard to troubleshoot and debug is as given below. The typical call stack looks as follows for the exception

Uncaught TypeError: Cannot read property 'type' of undefined
at bundle.js:64518
    at bundle.js:64518
    at Array.forEach (<anonymous>)
    at x (bundle.js:64518)

One can make out nothing from the call stack, it looks meaningless. Hence the debugging will be tedious job in ReactJS . 

Solution for the above exception

check whether return statement with dispatch is missing in your redux action method.

  return (function (dispatch) {

  });

Your action should have return statement as shown above.

More Read About ReactJS:

Advantages of React Stateless Functional Components

Advantages of React Stateless Functional Components

Before reading this post, if you have not gone through what are functional components in Reactjs then kindly go through this post

In this post we will see what are the advantages of functional posts in React js. If you check your react js code, you will quickly figure out that many components do not actually need state, they do get data from parent as props and will render the information. In such a case why to introduce state and make it complicated? rather I would prefer calling a function which returns me a component. Isn’t it so simple ? React 14 introduced Functional Components, also called as stateless components and removed unnecessary complications. So let us explore what are the advantages of stateless components 

Advantages of React Functional/Stateless Components: Ref

1. More focused on presentation

React is forcing us to write components which are used only for presentational purpose, these components are useful for dumb presentational purpose only, that focus on UI rather than behaviour. Technically speaking its normal tendency to go for stateful components, doing that way we are making our code easily hackable where every damn component keeps its own local state. Functional components allowing us to have pure components which just focus on presentation. where as the state is maintained by few higher level components.

2. Gain in Performance

Stateless components will bring performance gain since there is no state and lifecycle of a component. React doesn’t need to have unnecessary check and memory allocations which eventually brings performance boost.

3. Clean and Optimised Code

Stateless components reduce lot of code, almost 20% – 30% reduction in code and hence the code will become clean and optimised.

4. Easy to debug

Functional components are pure components and helps your to analyse your code quickly and you no need to put log if assert calls everywhere to debug. 

React more on React

React More on ReactNative 

Glimpse Of Intel AI & HPC Summit : Application’s Of Artificial Intelligence – Part 3

Glimpse Of Intel AI & HPC Summit : Application’s Of Artificial Intelligence – Part 3

Read my previous article Part 2

Intel demonstrated some of the great applications of Artificial Intelligence where Intel’s hardwares and softwares out performing to solve complex problems in realtime using AI. Intel is working with many customers to solve their complex problems. 

Application’s Of Artificial Intelligence

1. Tumour detection in large 3-D medical images

Identifying tumour from huge medical images is yet another complex problems, today we have algorithms which does this job better than doctors.

2. Disease Risk Prediction Using Genetic Variation Data

3. Classification and predictions of protein sequences

4. Intelligent Knowledge Management 

This is another interesting application where, the algorithms analyse the huge set of documents and help the management to answer for complex queries.

5. Oil Rig Inspector Assist System

This is a very complex problem, identifying corrosion on nut-bolts under deep sea water is a complex problem solve for oil mining industries. Currently it is a manual process, where video cameras are fixed in oil rig systems and several hundred people will manually go through thousands of frames of videos manually and identify the corrosion on nut-bolts.

Now Intel is working with such industries to automate the process by analysing the video frames. thousands of video frames will be analysed in just few hours. The algorithms are capable of identifying the corrosion with great precision.

6. Self driving Cars and Car automation

BMW CARASSO is the system based on ai, the company is using to collect data from several sensors to debug their hard systems and to achieve the quality in their product. Company is using this system only for their internal quality improvements and to understand the roads and behaviour of the cars.

Intel has lot of open source code base which can be used for many such applications, kindly see the source code of Intel’s Nervana in Github

Glimpse Of Intel AI & HPC Summit : Intel’s Vision For Artificial Intelligence Part 2

Glimpse Of Intel AI & HPC Summit : Intel’s Vision For Artificial Intelligence Part 2

Kindly read part 1 of this article .The next biggest step taken by Intel is bringing out Intel Xeon Platinum processor. This will bring a transformation in cloud computing, there are multiple benefits we gain from Xeon processors as given below.

Benefits Of Intel Xeon Processors:

Breakthrough Performance of Intel Xeon Platinum

Intel Xeon Breakthrough Performance
Intel Xeon Breakthrough Performance

Along with this Intel is addressing several issues to bring the speed in computing – the biggest problem in computing is the waiting time of the processor due to slow response of hard drives. Hard drives are very slower compared to processors and hence processors always waste their time to wait for hard drives.

Intel addressing the waiting time of processors through Intel’s 3D NAND technology and Intel OPTANE technology, through these technology we can bring highly responsive applications, highly responsive cloud storage.

Read More About Applications of AI: glimpse-of-intel-ai-hpc-summit-applications-of-artificial-intelligence-part-3

Glimpse Of Intel AI & HPC Summit : Intel’s Vision For Artificial Intelligence Part 1

Glimpse Of Intel AI & HPC Summit : Intel’s Vision For Artificial Intelligence

Thought of writing highlights of Intel AI & HPC Summit held in Bengaluru on 9Mar2018, The event was superb What is AI, What is current state of AI, What is future of AI. Now the whole world is talking a lot about AI , Artificial intelligence is transforming the industries, health care, transportation, education and our entire life style 🙂 There are lot of positive side of Artificial Intelligence but many people are afraid about the future, some even say Humanity may destroy either by natural disasters or by AI and some of the demos shown in yesterday’s summit also tend to think us in that way.

What is AI (Artificial Intelligence) ?

Well I do not give textbook definition for AI, because one google search on this topic will give you many definitions, here I would like to explain AI in simple way, humans are most intelligent animals on this planet, we invented machines to ease our life, we learn to manage and control the machines for our comfort, but that era is over, now we are onto a new transformation, machines are becoming smarter than humans, with no doubt one can say in future machines will control humans 🙂 thats all AI 

for your better understanding of AI, Intel defines as ” the key to machine intelligence is that it must be able to sense, reason, and act, then adapt based on experience.”

  • SenseIdentify and recognize meaningful objects or concepts in the midst of vast data. Is that a stoplight? Is it a tumor or normal tissue?
     
  • ReasonUnderstand the larger context, and make a plan to achieve a goal. If the goal is to avoid a collision, the car must calculate the likelihood of a crash based on vehicle behaviors, proximity, speed, and road conditions.
     
  • ActEither recommend or directly initiate the best course of action. Based on vehicle and traffic analysis, it may brake, accelerate, or prepare safety mechanisms.
     
  • AdaptFinally, we must be able to adapt algorithms at each phase based on experience, retraining them to be ever more intelligent. Autonomous vehicle algorithms should be re-trained to recognize more blind spots, factor new variables into the context, and adjust actions based on previous incidents.

What Does AI Look Today ?

 

 

What does AI look Today
What does AI look Today

 

Reference : How To Get Started as a Developer in AI

As per Prakash Mallya, Managing director – Sales and Marketing Group, Intel India Pvt Ltd, today the traffic due to ai, some stats shows as follows.

3000 GB per day from smart hospitals 

4000 GB per day from smart Cars

1, 000, 000 GB per day from connected factories

also 1 in 7 organisations adopting AI and the key sectors where AI is being adopted are,  BFSI (Banking Finance Services and Insurance) , Health care, Industries, Self driving cars etc. 

Intel’s Vision For AI

Intel is focusing on different aspects to emerge as leader in AI, it is not only building great products but it is creating the whole eco system to succeed in this AI era. Following are some of the key focus for Intel, which we can say building blocks for Artificial Intelligence

  1. Machine Learning

pcworld has detailed post about how Intel is mastering in machine learning through Intel’s Nervana, a Deep Learning Cloud and System. Nervana Cloud is a hosted platform designed to give organizations of all sizes the ability to quickly build and deploy deep-learning tools without having to invest in infrastructure equipment or a large team of experts. Based on neon, Nervana’s open-source deep-learning framework, the full-stack offering is optimized to handle complex machine-learning problems at scale

  2. Reasoning System

Another important building blog for AI is, reasoning system. Intel® Saffron™ uses human-like reasoning to find hidden patterns in data to enable confident decisions that deliver rapid return on investment (ROI).

  3. Computer Vision

Intel® Movidius™ VPUs drive the demanding workloads of  modern computer vision and AI applications at ultra-low power. By coupling highly parallel programmable compute with workload-specific hardware acceleration, and co-locating these components on a common intelligent memory fabric, Movidius achieves a unique balance of power efficiency and high performance. Movidius technology allows device makers to deploy deep neural network and computer vision applications in categories such as smartphones, drones, intelligent cameras and augmented reality devices.

  4. Depth Sensing

Intel® RealSense™ technology is fundamentally re-shaping the future of technology by equipping devices with the ability to see, understand, interact with, and learn from their environment.1 There are three products with depth perception technology that enable you to create new and innovative ways to connect with the world.

Read More : glimpse-of-intel-ai-hpc-summit-intels-vision-for-artificial-intelligence-part-2

React Native List View : Animate Rows While Scrolling Using FlatList

React Native List View : Animate Rows While Scrolling Using FlatList

In my previous post I have written about how to use React Native FlatList and we have seen the issues we face with pagination also how to add a loading indicator in the footer of FlatList. You can first read about it Link In this post we will see how to animate the rows while scrolling a FlatList.

Animating Rows In React Native FlatList :

To achieve animation for FlatList Rows, you have to install an npm module react-native-animatable, which provides variety of smooth animations for List Rows.

Installation of npm module:

$ npm install react-native-animatable --save

 

To make a continuous animation do this

<Animatable.Text animation="slideInDown" iterationCount={5} direction="alternate">Up and down you go</Animatable.Text>
<Animatable.Text animation="pulse" easing="ease-out" iterationCount="infinite" style={{ textAlign: 'center' }}>❤</Animatable.Text>

 

To animate rows in FlatList Rows do this

import * as Animatable from 'react-native-animatable';

class FlatListRow extends Component {
  render(){
    return(
      <Animatable.View animation='fadeInUp'>;
       <TouchableWithoutFeedback>;
          // here your row component
       </TouchableWithoutFeedback>;
      </Animatable.View>;
    );
  }
}

Variety of animations are supported in this React Native Animation library

React Native List View : Pagination With FlatList – Building A Great Scrollable List In React Native

React Native List View : Pagination With FlatList  – Building A Great Scrollable List In React Native

FlatList is is an interface used to render flat list, the component is provided by Facebook’s React Native Library

Handy features of FlatList are as follows

  1. It renders list of items if you just provide rendering View
  2. You can mention whether your list is horizontal or vertical, by default its vertical list view
  3. Configurable Callbacks provided 
  4. Header / Footer / Separator are supported by FlatList
  5. Pull To Refresh is made simple with React Native Flat List View
  6. Pagination is made easy using React Native Flat List view

How To Use React Native Flat List Component: With Loading symbol in Footer

<FlatList
          refreshing={this.state.refreshing}
          onRefresh={true}
          onEndReachedThreshold={0.5}
          onEndReached={({ distanceFromEnd }) => {
            //Call API to fetch next page of data
            console.log('on end reached ', distanceFromEnd);
          }}
          ListFooterComponent={(
            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
              <Spinner color='#6d4c41' />
              <Text>Loading please wait...</Text>
            </View>
          )}
          data={this.props.messages}
          renderItem={this.notificationContent.bind(this)}
          keyExtractor={(item) => item._id}
        />

React Native Pull To Refresh Using Flat List

Pull to refresh is made easy by just mentioning onRefresh = true and we should also mention refreshing = true while fetching new data 

Pagination Using Flat List In React Native

To achieve pagination mention onEndReachedThreshold some value between 0 – 1 and  a callback for onEndReached should be provided where we have a logic to call API to fetch next page of data

Official documentation of React Native FlatList has many more functionalities listed.

Issues with React Native FlatList or onEndReached doesn’t get fired

Some times pagination for FlatList doesn’t work as expected, onEndReached Will never get fired, or some times it will be called only first time when list is loaded. Possible reason for this behaviour would be keeping FlatList inside native base Container or Content, Keep FlatList inside View to fix the issue. 

Another possible solution to the issue of FlatList is changing onEndReachedThreshold value to a small number like 0.001.

Another Interesting solution which worked for me is giving height explicitly to the FlatList , this will call onEndReached callback

style={{ height: ( Dimensions.get(‘window’).height – 100 ) }}

Addressing The issue : React Native FlatList onEndReached called again and again

This can be addressed by ignoring the callback calls, this is can be done by using distanceFromEnd, if the value is +ve then do your pagination stuffs, if the value is    -ve then ignore the callback call. ReactNative FlatList returns +ve value when scroll reaches the end of the list. So the update code looks like below

<FlatList
          refreshing={this.state.refreshing}
          onRefresh={true}
          onEndReachedThreshold={0.5}
          onEndReached={({ distanceFromEnd }) => {
            if (distanceFromEnd >= 0) {
              //call API to get next page values
            }
            console.log('on end reached ', distanceFromEnd);
          }}
          data={this.props.messages}
          renderItem={this.notificationContent.bind(this)}
          keyExtractor={(item) => item._id}
        />


Also Explore React Native Exceptions

ReactNative Exception: TabNavigator expected a component class, got [object, object]

ReactNative Exception: TabNavigator expected a component class, got [object, object]

Possible cases to get ReactNative Error: ReactNative Exception: TabNavigator expected a component class, got [object, object] .

  1. When you are using a component with all small letters or a component that begin with small letter, Example

 

const FooterTabNavigation = TabNavigator(
  {
    Home: {
      screen: ({ screenProps, navigation }) => <homePage navigation={navigation} />
    },
 });

 

Solution : Use Capitalised class names, like HomePage navigation={navigation}

2. Another case is if by any chance you are using <div> component in ReactNative this exception might occur.
Example

const FooterTabNavigation = TabNavigator(
  {
    Home: {
      screen: ({ screenProps, navigation }) => <homePage navigation={navigation} />
    },
    TestScreen: {
      screen: ({ screenProps, navigation }) => <div />
    }
});

 

Solution : Do not use div tag in ReactNative instead use View

Explore More About React Native : React Native FlatList And Pagination

ReactJS : Functional or Stateless components

ReactJS : Functional or Stateless components

Many times you might come across a situation where React Component doesn’t need any state, which we call as stateless components. Thanks to React0.14 update, It introduced new types of react components with no state. 

React Stateless components are very much needed when the components is readonly doesn’t perform any operation other than just showing information.

How to Write React Functional component ?

React Functional Component Example: for stateless react component or a functional react component

const MessageBar = function(props) {
  return <p>Dear {props.username} you have completed the task successfully</p>;
};

The same component can nicely be written in one line using ES2015 standard as follows

const MessageBar = ({ username }) => <p>Dear {username} user, you have successfully completed the task</p>;

 

Conceptually components are like javascript functions here, they accept inputs as props, and return react elements. Functional components wherever required will also reduce load on redux since it is not required to maintain state for these components.

For more information on React functional components visit facebook react official site 

Check Advantages of React Functional Components

Also Check How to integrated Google Maps in reactJS : http://knowledge-cess.com/reactjs-google-map-component/

 

ReactJS: Google Map Component

ReactJS: Google Map Component

Steps to implement google maps in Facebook’s ReactJS Web Application

1. Add npm module in your project for react-google-maps

npm install --save react-google-maps # or
yarn add react-google-maps

 

Reference : https://github.com/tomchentw/react-google-maps

Before this you have to include google maps api sdk in your index.ejs file 

<script src=”https://maps.googleapis.com/maps/api/js?v=3.27&libraries=places,geometry&key=<YOUR_API_KEY>”></script>

How to get Google Maps Api Key ? 

Follow the steps given in this link

2. Create Google Map Handler Component

'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import update from 'react-addons-update';

import canUseDOM from 'can-use-dom';

import raf from 'raf';
import GoogleMapComponent from './gMapComponent';

const geolocation = (
  canUseDOM && navigator.geolocation ?
  navigator.geolocation :
  ({
    getCurrentPosition(success, failure) {
      failure('Your browser doesnt support geolocation.');
    },
  })
);

class GoogleMapHandlerComponent extends React.Component {

    state = {
      bounds: null,
      center: null,
      content: null,
      radius: 400,
      markers: []
    };

  constructor(props) {
    super(props);
    if (props !== null &&
        props !== undefined &&
        props.location !== null &&
        props.location !== undefined &&
        props.location.markers !== null &&
        props.location.markers !== undefined) {
      const locationInfo = {
        center: props.location.center,
        markers: props.location.markers
      };
      this.state = locationInfo;
    }
  }

  componentDidMount() {
    const tick = () => {
      if (this.isUnmounted) {
        return;
      }
      this.setState({ radius: Math.max(this.state.radius - 5, 0) });
      if (this.state.radius > 10) {
        raf(tick);
      }
    };
    geolocation.getCurrentPosition((position) => {
      if (this.isUnmounted) {
        return;
      }
      this.setState({
        center: {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        },
        content: 'Location found using HTML5.',
      });

      raf(tick);
    }, (reason) => {
      if (this.isUnmounted) {
        return;
      }
      this.setState({
        center: {
          lat: 60,
          lng: 105,
        },
        content: 'Error: The Geolocation service failed (${reason}).',
      });
    });

    if (document.getElementsByClassName('pac-container').length > 0) {
      const gmapSearchResultsBox = document.getElementsByClassName('pac-container')[0];
      gmapSearchResultsBox.style.zIndex = '2000';
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps !== null &&
        nextProps !== undefined &&
        nextProps.location !== null &&
        nextProps.location !== undefined &&
        nextProps.location.markers !== null &&
        nextProps.location.markers !== undefined) {
      this.setState({
        center: nextProps.location.center,
        markers: nextProps.location.markers
      });
    }
  }

  componentDidUpdate() {
    if (document.getElementsByClassName('pac-container').length > 0) {
      const gmapSearchResultsBox = document.getElementsByClassName('pac-container')[0];
      gmapSearchResultsBox.style.zIndex = '2000';
    }
  }
  componentWillUnmount() {
    this.isUnmounted = true;
  }

  isUnmounted = false;

 handleMapMounted = this.handleMapMounted.bind(this);
 handleBoundsChanged = this.handleBoundsChanged.bind(this);
 handleSearchBoxMounted = this.handleSearchBoxMounted.bind(this);
 handlePlacesChanged = this.handlePlacesChanged.bind(this);
 handleMarkerClose = this.handleMarkerClose.bind(this);
 handleMarkerClick = this.handleMarkerClick.bind(this);

 handleMapMounted(map) {
     this._map = map;
   }

   handleBoundsChanged() {
     this.setState({
       bounds: this._map.getBounds(),
       center: this._map.getCenter(),
     });
   }

   handleSearchBoxMounted(searchBox) {
     this._searchBox = searchBox;
   }
   handleLoadPlaces(markers) {

   }
   handlePlacesChanged() {
     const places = this._searchBox.getPlaces();

     // Add a marker for each place returned from search bar
     const markers = places.map(place => ({
       position: place.geometry.location,
     }));

     // Set markers; set map center to first search result
     const mapCenter = markers.length > 0 ? markers[0].position : this.state.center;
     this.setState({
       center: mapCenter,
       markers,
     });
     this.props.handleLocationChange(mapCenter, places);
   }

   // Toggle to 'true' to show InfoWindow and re-renders component
  handleMarkerClick(targetMarker) {
    this.setState({
      markers: this.state.markers.map(marker => {
        if (marker === targetMarker) {
          if (marker.showInfo) {
            return {
              ...marker,
              showInfo: false,
            };
          }
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
    });
  }

  handleMarkerClose(targetMarker) {
    this.setState({
      markers: this.state.markers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),
    });
  }

  render() {
    return (
      <GoogleMapComponent
        containerElement={
          <div style={{ height: '100%' }} />
        }
        mapElement={
          <div style={{ height: '100%' }} />
        }
        center={this.state.center}
        onMapMounted={this.handleMapMounted}
        onBoundsChanged={this.handleBoundsChanged}
        onSearchBoxMounted={this.handleSearchBoxMounted}
        bounds={this.state.bounds}
        onPlacesChanged={this.handlePlacesChanged}
        onMarkerClick={this.handleMarkerClick}
        onMarkerClose={this.handleMarkerClose}
        markers={this.state.markers}
      />
    );
  }
}

 function mapDispatchToProps(dispatch) {
   return bindActionCreators({ }, dispatch);
 }

export default connect(null, mapDispatchToProps)(GoogleMapHandlerComponent);

 

3. Create Google Map Component, this component uses the components of react-google-maps module

'use strict';

import React from 'react';
import IconButton from 'material-ui/IconButton';

import {
  withGoogleMap,
  GoogleMap,
  Circle,
  InfoWindow,
  Marker
} from 'react-google-maps';

import SearchBox from 'react-google-maps/lib/places/SearchBox';
import GoogleMapMarkerInfoWindow from './gMapMarkerInfoWindow';

import layoutStyle from '../../../constants/layoutStyle';

const INPUT_STYLE = {
  boxSizing: 'border-box',
  MozBoxSizing: 'border-box',
  border: '1px solid transparent',
  width: '240px',
  height: '32px',
  marginTop: '27px',
  marginRight: '20px',
  padding: '0 12px',
  borderRadius: '1px',
  boxShadow: '0 2px 6px rgba(0, 0, 0, 0.3)',
  fontSize: '14px',
  outline: 'none',
  textOverflow: 'ellipses',
};

const GoogleMapComponent = withGoogleMap(props => (
  <GoogleMap
    ref={props.onMapMounted}
    defaultZoom={15}
    center={props.center}
    onBoundsChanged={props.onBoundsChanged}
  >
    <SearchBox
      ref={props.onSearchBoxMounted}
      bounds={props.bounds}
      controlPosition={google.maps.ControlPosition.TOP_RIGHT}
      onPlacesChanged={props.onPlacesChanged}
      inputPlaceholder='Search Location'
      inputStyle={INPUT_STYLE}
    />

    {props.markers.map((marker, index) => (
      <Marker
        key={index}
        position={marker.position}
        onClick={() => props.onMarkerClick(marker)}
      >
        {/*
           Show info window only if the 'showInfo' key of the marker is true.
           That is, when the Marker pin has been clicked and 'onCloseClick' has been
           Successfully fired.
        */}
        {marker.showInfo && (marker.pinOnly === null ||
        marker.pinOnly === undefined || !marker.pinOnly) && (
          <InfoWindow onCloseClick={() => props.onMarkerClose(marker)}>
            <GoogleMapMarkerInfoWindow infoContent={marker.infoContent} />
          </InfoWindow>
        )}
      </Marker>
    ))}

    {props.center && (
      <Circle
        center={props.center}
        radius={props.radius}
        options={{
          fillColor: 'red',
          fillOpacity: 0.20,
          strokeColor: 'red',
          strokeOpacity: 1,
          strokeWeight: 1,
        }}
      />
    )}
  </GoogleMap>
));

export default GoogleMapComponent;


4. Use Google Map Handler component whereever you wish to place the map

render() {
      const handleLocationChange = this.handleLocationChange;
      const mapsComponent = (
        <GoogleMapHandlerComponent
          location={this.props.location}
          handleLocationChange={handleLocationChange.bind(this)}
        />);
      return (
        <div
          id='mapId'
          style={{ width: '450px', height: '350px' }}
        >
          {mapsComponent}
        </div>
      );
    }

Note you have to pass your current location to land user on his current location, else any other location which is default location.
and a callback for handling change in location.

ReactJS google map location change callback will be called by react-google-maps library when there is change in location,
like user searched some location

Also check stateless react components : http://knowledge-cess.com/reactjs-functional-or-stateless-components/