Saturday, 31 August 2019
Building application with react and redux
Why Redux?
Redux is a predictable state container for JavaScript applications. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. — https://redux.js.org/
Single Store-
Redux centralises all of your application states in a single store.
redux enforces keeping all states in single centralise object.
Redux is a state management tool. While it’s mostly used with React, it can be used with any other JavaScript framework or library.
each component can access any state that it needs from this store.
Reduced BoilerPlate-
your container component subscribe to redux store autometically so you dont have to wire up event emitter to subscribe to the dispatcher.
there is no dispatcher at all
Immutable store-
Hot reloading
small
Environment Build-
install Node-
Building app react Redux-
use my below blog to do the initial setup of project
https://javacmlearning.blogspot.com/2019/08/learn-react-js-setp-by-step.html
install visual studio
i am using prettier to format code.
after installing Prettier go to File ----> prefrences---->setting
search formatonsave and enable that.
Configure web-pack-
webpack became most popular bundler for react. it is extremely powerful.
webpack bundler compile java-script into a single minified file that works in browser.
webpack also includes development web server so server act locally during development using webpack.
webpack also use by creating react app behind the seen.
webpack configured javascript object.
config file is called webpack.config.js and is placed in project root.
webpack.config.js
Redux is a predictable state container for JavaScript applications. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. — https://redux.js.org/
Single Store-
Redux centralises all of your application states in a single store.
redux enforces keeping all states in single centralise object.
Redux is a state management tool. While it’s mostly used with React, it can be used with any other JavaScript framework or library.
each component can access any state that it needs from this store.
Reduced BoilerPlate-
your container component subscribe to redux store autometically so you dont have to wire up event emitter to subscribe to the dispatcher.
there is no dispatcher at all
Immutable store-
Hot reloading
small
Environment Build-
install Node-
Building app react Redux-
use my below blog to do the initial setup of project
https://javacmlearning.blogspot.com/2019/08/learn-react-js-setp-by-step.html
install visual studio
i am using prettier to format code.
after installing Prettier go to File ----> prefrences---->setting
search formatonsave and enable that.
Configure web-pack-
webpack became most popular bundler for react. it is extremely powerful.
webpack bundler compile java-script into a single minified file that works in browser.
webpack also includes development web server so server act locally during development using webpack.
webpack also use by creating react app behind the seen.
webpack configured javascript object.
config file is called webpack.config.js and is placed in project root.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
};
Redux ,Action stores and Reducers
Redux
A predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.
Redux is a valuable tool for organising your state
Here are some suggestions on when it makes sense to use Redux:
- You have reasonable amounts of data changing over time
- You need a single source of truth for your state
- You find that keeping all your state in a top-level component is no longer sufficient
PredictableRedux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.
CentralizedCentralizing your application's state and logic enables powerful capabilities like undo/redo, state persistence, and much more.
DebuggableThe Redux DevTools make it easy to trace when, where, why, and how your application's state changed.
FlexibleRedux works with any UI layer, and has a large ecosystem of addons to fit your needs.
Redux : 3 Principals
1.One Immutable Store: Application state is placed in single immutable store, state can be changed directly having one immutable store its debugging,server rendering, and it makes things like undo and redo.
in redux the only way to change state is making an action.
2.Action Triger Changes:
user may trigger some submit button may trigger some action
3. Reducers Update State:
state changes are handled by true functions these are called reducers.in redux reducers are just function that accept the current state and an action and return a new state.
Flux Vs Redux:
flux and redux are two different ways to handle state and data flows in your react application.
both having same unidirectional data flow concept
data flows down action flows up
Similarity-
- Unidirectional Flow
- Action
- stores
Redux new Concepts-
1.Reducer
function that takes current states and actions and then return a new state.
2.Containers-
containers are just react component.used specific .
container component have necessary logics for marshalling data and actions.
3.immutablility
redux storea are immutable
Flux:
when action is triggered store is notified by dispatcher.flux uses singelton dispatcher to connect actions to store.
store use event emitter to connect to the dispatcher.
Redux:
redux doesn't have dispatcher ,redux relies on pure functions called reducers so it doesn't need dispatcher .
pure functions are easy to compose
each action is automatically handled by one or more reducer which update the single store. since state is immutable in redux reducer returns a new updated copy of state which update the store
Action- action describes users intent. that is an object with type property and data.
data portion can be whatever you like. action having type property is mandatory.
Example-
below is the action for course rating , in this you have to rate a course from scale of 1 to 5.
{type: RATE_COURSE,rating:5}
data portion on right (rating ) can be whatever you want ,you can pass multiple seprate peaces of data here or one or more separate object.
Reducer-
This action automatically handled by reducers .reduces is a function that return new state.
it will receive current state and action and return a new state. it typically uses a switch statement that checks type of action this determine new state could be returned.
function appReducer(state=defaultstate,action)
{
switch(action.type)
{
case RATE_COURSE:
//return new state
}
}
as soon as new state is returned from reducer store is updated.react rerender any component that is utilising the data.
Notified via React Redux
new react component is connected with the store using a redux related library called react redux.
Difference between flux and Redux
Action Creators-
in Redux the event happening on application is called actions . actions are just plain objects containing a descriptions of an event.
reateCourse(rating) // Action creator
{
type:RATE_COURSE,
rating: rating //Action
}
Creating Redux Store-
let store= createStore(reducer)
we pass create store function to reducer function ,it work on single responsibility principle store only store data of reducers which will discuss in a moment.handle state changes.
store can
dispatch an action store.dispatch(action)
subscribe to the listener store.subscribe(listener)
return its current state store.getState()
replace reducer replaceReducer(nextReducer)
Immutability :
to change state,return new object
already immutable objects:
Number
String
Boolean
undefiend
null
Mutable
Object
Arrays
Function
Handling Immutable data in JS
1. Ojbect.assign object.assign
creates new object or allow us to specify existing objects as a template.
first parameter is target and then it can accept as many source objects as you want.
Ojbect.assign(target, ...sources)
Example
Object.assign({},state,{role:'admin'});
explanation:
first paramenter is target so it will just create a new empty object.
then it is mixing the new object with existing state.
also changing role property to admin.
2.spread Operator {.....myObj...}
you can also use array,
const newUser =[...states.users]
immutable array .map
methods
(map,filter,reduce)
Handling Arrays:
always prefer - map,filter,reduce,concat,spread
avoid-push,pop,reverse
Action Creators-
in Redux the event happening on application is called actions . actions are just plain objects containing a descriptions of an event.
reateCourse(rating) // Action creator
{
type:RATE_COURSE,
rating: rating //Action
}
Creating Redux Store-
let store= createStore(reducer)
we pass create store function to reducer function ,it work on single responsibility principle store only store data of reducers which will discuss in a moment.handle state changes.
store can
dispatch an action store.dispatch(action)
subscribe to the listener store.subscribe(listener)
return its current state store.getState()
replace reducer replaceReducer(nextReducer)
Immutability :
to change state,return new object
already immutable objects:
Number
String
Boolean
undefiend
null
Mutable
Object
Arrays
Function
Handling Immutable data in JS
1. Ojbect.assign object.assign
creates new object or allow us to specify existing objects as a template.
first parameter is target and then it can accept as many source objects as you want.
Ojbect.assign(target, ...sources)
Example
Object.assign({},state,{role:'admin'});
explanation:
first paramenter is target so it will just create a new empty object.
then it is mixing the new object with existing state.
also changing role property to admin.
2.spread Operator {.....myObj...}
you can also use array,
const newUser =[...states.users]
immutable array .map
methods
(map,filter,reduce)
Handling Arrays:
always prefer - map,filter,reduce,concat,spread
avoid-push,pop,reverse
Sunday, 25 August 2019
Securing React Apps
Securing ReactApp with Auth0
securing reactapp is having two concerns
1-Authentication ? who are you
Login with email id and password
2-Authorization? what are you allowed to do
check user rights
popular Auth providers-
Auth0
Okta
what needed to do to setup OAuth
you need to register your react app with the service provider.
you will give them infor- appname, website ,callback url
OAuth Rules-
we need to understand 4 key roles in OAuth
1- Resource owner (User)- account owner ,so if you are a user trying to login to react app you are considering resource owner.
2-Client (App) -
client is the app that wants to access the user account .
user must be off the client permission to do so.
3- AuthServer (Auth logic)
Auth0
4- Resource Server (user data)
this is the api application want to access
JSON web token(JWT)
Access Token
Used for authorization and info exchange
Often contains user info
Pronounced “JOT”
Digitally signed
Can be encrypted
Why JWT over SAML?
JSON is less verbose than XML
Smaller when encoded too
Easier to sign than SAML
JSON is easy to parse on the client
JWT Parts
securing reactapp is having two concerns
1-Authentication ? who are you
Login with email id and password
2-Authorization? what are you allowed to do
check user rights
popular Auth providers-
Auth0
Okta
what needed to do to setup OAuth
you need to register your react app with the service provider.
you will give them infor- appname, website ,callback url
OAuth Rules-
we need to understand 4 key roles in OAuth
1- Resource owner (User)- account owner ,so if you are a user trying to login to react app you are considering resource owner.
2-Client (App) -
client is the app that wants to access the user account .
user must be off the client permission to do so.
3- AuthServer (Auth logic)
Auth0
4- Resource Server (user data)
this is the api application want to access
OAuth 2.0 terminology
- Resource Owner: the entity that can grant access to a protected resource. Typically this is the end-user.
- Client: an application requesting access to a protected resource on behalf of the Resource Owner.
- Resource Server: the server hosting the protected resources. This is the API you want to access.
- Authorization Server: the server that authenticates the Resource Owner, and issues Access Tokens after getting proper authorization. In this case, Auth0.
- User Agent: the agent used by the Resource Owner to interact with the Client, for example a browser or a native application.
OAuth is for authorization - No standard for scopes and user info requests
It would be nice to avoid managing passwords ourselves
Authenticate users without managing passwords
Can you send and receive JSON over HTTP?
Then you can implement OpenID Connect from scratch.
Access Token
Used for authorization and info exchange
Often contains user info
Pronounced “JOT”
Digitally signed
Can be encrypted
Why JWT over SAML?
JSON is less verbose than XML
Smaller when encoded too
Easier to sign than SAML
JSON is easy to parse on the client
JWT Parts
Saturday, 24 August 2019
React Fundamentals
What is React-
focused on providing -
Composable components : React components are simple interface defined input as properties and output as call backs .by implementing component react component can freely nest with each other.
What are the advantage and disadvantage of React application?
Advantages Disadvantages
Conceptual simplicity: a React application is a tree Limited in scope
of react components. react component is a function
that is having model object of basic user interface.
speed- react is optimise for simplicity Productivity
Simple model for server-side rendering Complex tooling
input to the components are properties refers to props and states.
difference between two is state can change .
props refers model.
once document object model render it generate events it back into component state and trigger another render cycle.
react maintain its document abstractions component Render function update this fake DOM(virtual dom) which is extremely fast.once that happen it is job of the react founder to compare this dom to count state of real dom and update the real dom in most efficient possible way.
what are the Differences between angular js and React js?
Reactjs Angularjs
Render UI and handle events A complete UI framework
User java script for view logic Custom "Template Expression" syntax
javascript TypeScript
What is component?
Component are the fundamental unit of react application.each component corresponds to the elements in the DOM.
component is responsible for rendering the content of the elements and handling any events .
components can be nested inside other components.
nested components correspondes to nested dom nodes.
Defining Components
Rendering Components
props
Component life cycle
state
Defining a Component
this is how we define simple react component. value retrun from function is actually jsx a special markup languate which react compiles to java script. this is one of the key syntext
function Hello(props){
return <h1>Hello at {props.now}</h1>;
}
Rendering a component-
import ReactDOM from 'react-dom';
“All React components must act
like pure functions with respect
to their props.”
Class Components
class Sum extends React.Component {
render() {
return <h1>
{props.a} + {props.b} = {props.a + props.b}
</h1>;
}
}
ReactDOM.render(<Sum a={4} b={2} />,
document.getElementById('root')
);
The primary reason to choose class components over functional components is that they can have
Class components should always call the base constructor with
The traditional way is to use
ES6 introduced a syntax that allows you to write classes that extend
Mounting
constructor -> componentWillMount -> render -> componentDidMount
Updating
componentWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate
Properties validation:
function Sum(props) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
ReactDOM.render(<Sum a={4} b={2} />,
document.getElementById('root')
);
output= 6
function Sum(props) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
ReactDOM.render(<Sum a={“key”} b={“board”} />,
document.getElementById('root')
);
output
key+board= keyboard
function Sum(props) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
ReactDOM.render(<Sum a={“a”} b={2} />,
document.getElementById('root')
);
output:
a+2=a2
how to constraints a and b to be numbers?
react component can validate proptype , this is run time validation
import PropTypes from 'prop-types’;
function Sum(props) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
Sum.propTypes = {
a: PropTypes.number.isRequired,
b: PropTypes.number.isRequired,
};
ReactDOM.render(<Sum a={“a”} b={2} />,
document.getElementById('root')
);
TypeScript and Flow
Argument of type '{ a: string; b: number; }' is not assignable to parameter of type 'SumProps'. Types of property 'a' are incompatible. Type 'string' is not assignable to type 'number'.
interface SumProps {
a: number;
b: number;
}
function Sum(props: SumProps) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
ReactDOM.render(<Sum a={“a”} b={2} />,
document.getElementById('root')
);
What is JSX?
Supports xml-like syntax in JavaScript Each element is transformed into a JavaScript function call
JSX
<Sum a={4} b={3} />
JavaScript
React.createElement(
Sum,
{a:4, b:3},
null
)
2-
<h1>
<Sum a={4} b={3} />
</h1>
java Script
React.createElement(
‘h1’,
null,
React.createElement(
Sum,
{a:4, b:3},
null
)
)
<label
for="name"
class="highlight"
style="backgroundcolor: yellow"
>
Foo Bar
</label>
JSX elements can be nested
<Hello>
<First />
<Second />
</Hello>
How many ways we can create react component?
we can create react component by 4 ways-
1-Container
2-Presentational
React,Redux
React-redux is separate library .
Provider- attaches app to store
wrapping your app in provider makes the Redux store accessible to every component in your app.
<provider store={this.props.store}
<app/>
</provider>
Connect-creates container components.
wrap our components so its connected to redux store.
export default connect(mapStateToProps,mapDispatchToProps)(AuthorPage)
mapStateToProps-> what state do you want to pass to components
mapDispatchToProps--> what action do you want to pass to your component
Benifits:
focused on providing -
rendering and event handling functionality - rendering is conversion of data that describes the user interface into document object model object.that the browser can use to produce the user interface.that the user can see and interact with.this is similar to view engines like handlebar .
event handling lets the programmer to interact with user interface as per the program and specify how the program should respond.
React is created and maintained by Facebook
React is architect-ed mainly for
React is architect-ed mainly for
- functional programming
- one way data flow: it simplify programming and user interfaces
- virtual Dom: java script object model
- relies on javascript
Composable components : React components are simple interface defined input as properties and output as call backs .by implementing component react component can freely nest with each other.
What are the advantage and disadvantage of React application?
Advantages Disadvantages
Conceptual simplicity: a React application is a tree Limited in scope
of react components. react component is a function
that is having model object of basic user interface.
speed- react is optimise for simplicity Productivity
Simple model for server-side rendering Complex tooling
input to the components are properties refers to props and states.
difference between two is state can change .
props refers model.
once document object model render it generate events it back into component state and trigger another render cycle.
react maintain its document abstractions component Render function update this fake DOM(virtual dom) which is extremely fast.once that happen it is job of the react founder to compare this dom to count state of real dom and update the real dom in most efficient possible way.
what are the Differences between angular js and React js?
Reactjs Angularjs
Render UI and handle events A complete UI framework
User java script for view logic Custom "Template Expression" syntax
javascript TypeScript
What is component?
Component are the fundamental unit of react application.each component corresponds to the elements in the DOM.
component is responsible for rendering the content of the elements and handling any events .
components can be nested inside other components.
nested components correspondes to nested dom nodes.
Defining Components
Rendering Components
props
Component life cycle
state
Defining a Component
this is how we define simple react component. value retrun from function is actually jsx a special markup languate which react compiles to java script. this is one of the key syntext
function Hello(props){
return <h1>Hello at {props.now}</h1>;
}
Functional Components
Functional components are just JavaScript functions. They take in an optional input which, as I've mentioned earlier, is what we call props.
import ReactDOM from 'react-dom';
import React from 'react’;
function Hello(props) {
return <h1>Hello at {props.now}</h1>;
}
ReactDOM.render(<Hello now={new Date().toISOString()} />,
document.getElementById('root')
);
jsx is markup language that looks like html but can be specify inside javascript code.we can use render function to use react dom module to render a react component in to dom element.
1st arugument is jsx expression , 2nd argument is dom element the react component will be inserted in this dom element.
Props
ReactDOM.render(<div id=“mydiv”></div>,
document.getElementById('root')
);
props = {
a: 4,
b: 2
}
function Sum(props) {
return (
<h1>{props.a} + {props.b} = {props.a + props.b}</h1>
);
}
ReactDOM.render(<Sum a={4} b={2} />,
document.getElementById('root')
);
Class Components
class Sum extends React.Component {
render() {
return <h1>
{props.a} + {props.b} = {props.a + props.b}
</h1>;
}
}
ReactDOM.render(<Sum a={4} b={2} />,
document.getElementById('root')
);
The primary reason to choose class components over functional components is that they can have
state
.Class components should always call the base constructor with
props
.There are two ways that you can create a class component.
The traditional way is to use React.createClass()
.
ES6 introduced a syntax that allows you to write classes that extend React.Component
.
Class components can exist without state too.
class
Hello
extends
React.Component {
constructor(props) {
super
(props);
}
render() {
return
(
<div>
Hello {props}
</div>
)
}
}
We define a constructor method that accepts props as input. Inside the constructor, we call super() to pass down whatever is being inherited from the parent class.
First, the constructor is optional while defining a component. In the above case, the component doesn't have a state, and the constructor doesn't appear to do anything useful.
this.props
used inside the render()
will work regardless of whether the constructor is defined or not.
Secondly, if you're using a constructor, you need to call
super()
. This is not optional, and you will get the syntax error "Missing super() call in constructor" otherwise. Component Lifecycle
Mounting
constructor -> componentWillMount -> render -> componentDidMount
Updating
componentWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate
State:
Alternative component data container
State is local, mutable data
class ClickCounter extends React.Component {
constructor(props) {
super(props);
this.state = {clicks: 0};
}
render() {
return <div onClick={() =>
{ this.setState({clicks: this.state.clicks + 1}); }}>
This div has been clicked {this.state.clicks} times.
</div>;
}
to use state we have to use class component.we initialize component state to default.
int the class constructor we initalize component types to default.
here initialise the clicks property with zero.when we display the click count we read the value from state property {this.state.clicks} from props because clicks is internal state value not an external props value.
setState
Previous state
{
a: 1,
b: 2
}
State change
this.setState({
b: 3,
c: 4
});
New state
{
a: 1,
b: 3,
c: 4
}
Properties validation:
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
ReactDOM.render(<Sum a={4} b={2} />,
document.getElementById('root')
);
output= 6
function Sum(props) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
ReactDOM.render(<Sum a={“key”} b={“board”} />,
document.getElementById('root')
);
output
key+board= keyboard
function Sum(props) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
ReactDOM.render(<Sum a={“a”} b={2} />,
document.getElementById('root')
);
output:
a+2=a2
how to constraints a and b to be numbers?
react component can validate proptype , this is run time validation
import PropTypes from 'prop-types’;
function Sum(props) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
Sum.propTypes = {
a: PropTypes.number.isRequired,
b: PropTypes.number.isRequired,
};
ReactDOM.render(<Sum a={“a”} b={2} />,
document.getElementById('root')
);
TypeScript and Flow
Argument of type '{ a: string; b: number; }' is not assignable to parameter of type 'SumProps'. Types of property 'a' are incompatible. Type 'string' is not assignable to type 'number'.
interface SumProps {
a: number;
b: number;
}
function Sum(props: SumProps) {
return <h1>{props.a} + {props.b} = {props.a + props.b}</h1>;
}
ReactDOM.render(<Sum a={“a”} b={2} />,
document.getElementById('root')
);
What is JSX?
Supports xml-like syntax in JavaScript Each element is transformed into a JavaScript function call
JSX
JavaScript
React.createElement(
Sum,
{a:4, b:3},
null
)
2-
<h1>
<Sum a={4} b={3} />
</h1>
java Script
React.createElement(
‘h1’,
null,
React.createElement(
Sum,
{a:4, b:3},
null
)
)
Spread Attributes
const props = {a: 4, b: 2};
const element = <Sum {...props} />;
Events
function Clicker({ handleClick }) {
return <button onClick={(e)=>{handleClick('A');}}>A</button>
}
const el = <Clicker handleClick={(l) => {log(l);}} />;
JSX
<label
htmlFor="name"
className="highlight"
style={{
backgroundColor:
"yellow”
}}
>
Foo Bar
</label>
HTML
<label
for="name"
class="highlight"
style="backgroundcolor: yellow"
>
Foo Bar
</label>
JSX elements can be nested
<Hello>
<First />
<Second />
</Hello>
How many ways we can create react component?
we can create react component by 4 ways-
- create class
- ES class
- function
- Arrow function
Reduc,action stores and Reducers
React components are mainly of two types1-Container
2-Presentational
React,Redux
React-redux is separate library .
Provider- attaches app to store
wrapping your app in provider makes the Redux store accessible to every component in your app.
<provider store={this.props.store}
<app/>
</provider>
Connect-creates container components.
wrap our components so its connected to redux store.
export default connect(mapStateToProps,mapDispatchToProps)(AuthorPage)
mapStateToProps-> what state do you want to pass to components
mapDispatchToProps--> what action do you want to pass to your component
Benifits:
- no manual unsubscribe
- Declare what subset of state you want
- Enhance performence for free
React-Redux Component-
Subscribe to:
Posts (Atom)