Monday, 31 January 2022

How to check data type or validate data in React js

 there are two data types in Javascript 

primitive 


String, 

Number, 

Boolean, 

Undefined, 

and NULL 


non-primitive types:

Object,

 Array,

 and RegExp

 To check the data belongs to which data type there is an inbuilt javascript method called typeof. typeof can be used for validating the data type but there is one weird behavior of typeof Array that it gives us object as output.

console.log(typeof(new Date())) // object

console.log(typeof(['Manish', 'Manntrix', "Medium"])) // object

console.log(typeof({ name: 'Manish', age: 26 })) // object

console.log(typeof(/ab+c/i)) // object

console.log(typeof(new Error('Error')))  // object


To solve the issue 

  1. Open your project directory and install xtypejs.
npm install xtypejs --save

2. Now import xtype from xtypejs library.

import xtype from 'xtypejs'
console.log(xtype(new Date())) // date console.log(xtype({})) // empty_object
console.log(xtype({name: "manish"})) // single_prop_object
console.log(xtype({name: "manish", age: 26})) // multi_prop_object
console.log(xtype([])) // empty_array
console.log(xtype([1])) // single_elem_array
console.log(xtype([1, 2])) // multi_elem_array
console.log(xtype(undefined)) //undefined
console.log(xtype(1)) //positive_integer
console.log(xtype(1.1)) //positive_float
console.log(xtype(-1.1)) //negative_float
console.log(xtype(-1)) //negative_integer
console.log(xtype('Hello')) //multi_char_string
console.log(xtype(' ')) //whitespace
console.log(xtype('')) //empty_string
console.log(xtype(NaN)) //nan
console.log(xtype(new Error())) //error
console.log(xtype(/ab+c/i)) //regexp
console.log(xtype(true)) //true
console.log(xtype(false)) //false

//Example 2 (Validate with correct data type) ============================================== console.log(xtype.type(new Date())) // date
console.log(xtype.type({})) // object
console.log(xtype.type({name: "manish"})) // object
console.log(xtype.type({name: "manish", age: 26})) // object
console.log(xtype.type([])) // array
console.log(xtype.type([1])) // array
console.log(xtype.type([1, 2])) // array
console.log(xtype.type(undefined)) //undefined
console.log(xtype.type(1)) //number
console.log(xtype.type(1.1)) //number
console.log(xtype.type(-1.1)) //number
console.log(xtype.type(-1)) //number
console.log(xtype.type('Hello')) //string
console.log(xtype.type(' ')) //string
console.log(xtype.type('')) //string
console.log(xtype.type(NaN)) //nan
console.log(xtype.type(new Error())) //error
console.log(xtype.type(/ab+c/i)) //regexp
console.log(xtype.type(true)) //boolean
console.log(xtype.type(false)) //boolean
Full e-g
Class component ;eve; constructor(props){
super
(props)
this.state = {
data: []
}
} Hooks level - function component const[ApiData, setApiData ] useState([]); useEffect({ getData(); },[])
async getData (){
const res = await axios.get('https://jsonplaceholder.typicode.com/users')
if(xtype.type(res.data) === 'array'){
this.setState({data: res.data})
}else{
console.log(new Error('Something went wrong'))
this.setState({data: []})
}
}
componentDidMount(){
this.getData()
}
render() {
return (
<div>
{this.state.data.map(d => <h5>{d.name}</h5>)}
</div>
)
} Ref: https://medium.com/how-to-react/how-to-check-data-type-or-validate-data-in-react-js-a172eceed8a8#:~:text=String%2C%20Number%2C%20Boolean%2C%20Undefined,inbuilt%20javascript%20method%20called%20typeof.

Wednesday, 21 July 2021


How to resolve JavaScript Cross Browser Compatibility Issues

 

Why is JavaScript browser compatibility an issue in the first place?

Early on, in the 1990s, the two main browsers globally used were Internet Explorer and Netscape implemented scripting in fundamentally different ways – Netscape used JavaScript, IE used JScript and also offered VBScript. JavaScript and JScript have some level of alignment since they both functioned on the ECMAScript specification. But on multiple levels, the code was implemented in contrasting and even conflicting ways, which made developing for both browsers exceptionally tedious.

Even into the 2000s, browser compatibility remained a concern for JavaScript. Since every browser runs a unique rendering engine, web elements are processed and displayed in different ways. Libraries like jQuery have made things easier by resolving and eliminating differences in how JS is implemented in various browsers. Consequently, devs only have to generate one block of code and let the library reconcile browser-based differences in the background.

However, errors in JS due to browser differences continue to plague developers. Though their occurrence is less frequent than before, they still need to be dealt with quickly and cohesively. This article will explore these issues and offer a few solutions for the same.



Common Javascript Browser Compatibility Issues

  • Primarily errors in JavaScript browser compatibility pop up when website developers try to use modern JavaScript features that are not supported on older browsers or browser versions. For example, ECMAScript 6 / ECMAScript Next is not supported in IE11. In case, you want to test your website compatibility on older browser versions, check this out. Any feature implemented with ES6 will essentially not work on this browser. A few examples of newer JS features unsupported on older browsers are:
    1. Promises are excellent for executing asynchronous operations, but they are not supported in IE.
    2. Arrow functions offer a more concise and usable syntax to craft anonymous functions. It is not supported on IE and Safari.
    3. On declaring Strict mode on top of JS code, it is parsed more rigorously with numerous rules, causing more warnings and errors to be flagged. Using Strict mode creates cleaner and more efficient code. But it isn’t supported uniformly across all browsers.
    4. With typed arrays, JS code can access and modify raw binary data. Along with modern browsers, this feature is only supported by IE10 and above. Did you know, how to test your website on the latest IE versions?

    Several necessary APIs are also unsupported on older browsers – IndexedDB API, Web Storage API, Web Workers API, WebGL API, Web Audio API, WebRTC API, WebVR API.


How to solve Javascript Browser Compatibility Issues?

  • To start with, devs must figure out if a JavaScript function is compatible with older browsers and browser versions. Use online tools like caniuse to identify which feature is supported on which browser/version and code accordingly.
  • Use JavaScript Transpiling: Transpiling converts JS code using the latest features (ES6, for example) to code suitable for older browsers. There are tools for JS transpiling such as Babel, which makes this a piece of cake.
  • Use Polyfills: These are third-party JS files that work similarly to JS libraries. However, polyfills are also capable of providing new functionalities. For example, a polyfill can be used to support ES6-based features in browsers that fundamentally don’t.
  • Use Linters: A linter scrutinizes code to check for bugs, programming errors, stylistic anomalies, undeclared variables, and the like. JS linters go a long way in maintaining code quality without requiring human validation. It is possible to adjust linters to certain levels of scrutiny, AKA error flagging/reporting. Popular JS linters include JSLint and ESLint. It is advisable to download a code editor with a built-in linter plugin applicable to JavaScript code. Atom, an open-source IDE, is quite helpful in this regard. It allows devs to install JSLint, among others, to comb through their source code.
  • Use browser developer tools/dev tools that help to debug JavaScript. In most browsers, the JavaScript console will flag and report errors in code. Use the Console API to allow JS source code to communicate with the browser’s JS console. Console API’s most widely used feature is console.log(), but study and apply its other functions to increase debugging efficiency.
  • Use the JavaScript debugger (Firefox), Chrome DevTools (Chrome), Safari Web Development Tools (Safari), and similar counterparts to delve deeper into the code and add breakpoints – junctures where code execution stops, and the developer can examine its operation in the environment so far.
  • Check browser compatibility of JavaScript by testing websites on real browsers. All the debugging in the world will not match up to the ease and accuracy of monitoring website behavior in real user conditions. Among many other reasons, detecting browser compatibility flaws in JS code makes cross browser testing indispensable in website development.
RRef: 
https://www.browserstack.com/guide/resolve-javascript-cross-browser-compatibility-issues

Claude Code worflow

The Claude code task cycle 1. Gater context Reads files, explore projec structure, code base 2. Plan Break the task in to steps 3. Exe...