Wednesday, October 30, 2019

MERN

MERN

client
server

Step :#1
cd client
client > npx create-react-app .
npm start


Step :#2
cd server 
npm init -y    [ -y  means no questions]
yarn add  bcrypt dotenv express express-validator jsonwebtoken mongoose
yarn add concurrently nodemon --dev

Step :#3

Step :#4

Step :#5

Step :#6

Step :#7

Step :#8
Step :#9
...............................................................................................................................................................................................................................
Step :#10

Stpe: #1  [ create a new project and Install lib]

npm init -y
yarn add express cors
yarn global add nodemon


Stpe: #2  [ Code for Server Side]

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())
app.get('/', (req, res) => {
    res.send({ message: "Hello world!" })
})
const port = process.env.PORT || 5000
app.listen(port, () => {
    console.log(`Server running on port ${port}`)
})

Stpe: #3  [ run the server]

nodemon server

Stpe: #4 create a new project and Install lib]
npx create-react-app client
yarn add axios

Stpe: # 5 [ Code ]

import React from 'react'

import Axios from 'axios'

const Home = () => {

  Axios({
    method: 'GET',
    url: 'http://localhost:5000/',
    headers: {
      "Content-Type": "application/json"
    }
  }).then(response => {
    console.log(response.data.message)
  })
  return (
    <>
    </>
  )}
const App = () => {
  return (
    <Home />
  )
}
export default App

Stpe: # 5 [ run the react project]

yarn start





Happy Coding :)
...............................................................................................................................................................................................................................
Example: #2

import React, { Component } from 'react';
import Axios from 'axios';

const Api = Axios.create({
    method: 'GET',
    baseURL: 'http://localhost:5000',

})
export default class App extends Component {
    render() {
        Api.get('/', {
            headers: {
                'Content-Type': 'application/json'
            },
        }).then(({ data }) => console.log(data))
            .catch(error => console.log(error))
        return (
            <>
                <h3> Hello World</h3>
            </>
        )
    }
}
Happy Coding :)
............................................................................................................................................................................................................................
Example: #3  [ call inside constructor ]

import React, { Component } from 'react';
import Axios from 'axios'

const Api = Axios.create({
    method: 'GET',
    baseURL: 'https://jsonplaceholder.typicode.com/users',
})

export default class App extends Component {
    constructor(props) {
        super(props)
        this.fetchData()
        this.state = {
            users: []
        }
    }

    // componentDidMount() {
    //     this.fetchData()
    // }

    fetchData = async () => {
        try {
            let data = await Api.get('/')
                .then(({ data }) => data)
            console.log(data)
            this.setState({ users: data })
        } catch (error) {
            console.log(error)
        }
    }
    render() {
        return (
            <>
                {this.state.users.map((i, index) => {
                    return (
                        <div key={index}>
                            <h4 key={i}>{i.name}</h4>
                        </div>
                    )
                })}
            </>
        )
    }
}
Happy Coding :)
............................................................................................................................................................................................................................
Example: #4

















Happy Coding :)
............................................................................................................................................................................................................................
Example: #5






Happy Coding :)
............................................................................................................................................................................................................................
Example: #6



Happy Coding :)
............................................................................................................................................................................................................................
Example: #7











Monday, October 21, 2019

error Invalid regular expression

Example : #1

error Invalid regular expression: /(.*\\__fixtures__\\.*|node_modules[\\\]react[\\\]dist[\\\].*|website\\node_modules\\.*|heapCapture\\bundle\.js|.*\\__tests__\\.*)$/: Unterminated character class. Run CLI with --verbose flag for more details.
SyntaxError: Invalid regular expression: /(.*\\__fixtures__\\.*|node_modules[\\\]react[\\\]dist[\\\].*|website\\node_modules\\.*|heapCapture\\bundle\.js|.*\\__tests__\\.*)$/: Unterminated character class
    at new RegExp (<anonymous>)
    at blacklist (C:\Users\sapan\Desktop\React Native\demo\node_modules\metro-config\src\defaults\blacklist.js:41:10)
    at getBlacklistRE (C:\Users\sapan\Desktop\React Native\demo\node_modules\@react-native-community\cli\build\tools\loadMetroConfig.js:66:59)
    at getDefaultConfig (C:\Users\sapan\Desktop\React Native\demo\node_modules\@react-native-community\cli\build\tools\loadMetroConfig.js:82:20)
    at load (C:\Users\sapan\Desktop\React Native\demo\node_modules\@react-native-community\cli\build\tools\loadMetroConfig.js:118:25)
    at Object.runServer [as func] (C:\Users\sapan\Desktop\React Native\demo\node_modules\@react-native-community\cli\build\commands\server\runServer.js:82:58)
    at Command.handleAction (C:\Users\sapan\Desktop\React Native\demo\node_modules\@react-native-community\cli\build\index.js:164:23)
    at Command.listener (C:\Users\sapan\Desktop\React Native\demo\node_modules\commander\index.js:315:8)
    at Command.emit (events.js:210:5)

    at Command.parseArgs (C:\Users\sapan\Desktop\React Native\demo\node_modules\commander\index.js:651:12)


................................................................................................................................

Solutions -


\node_modules\metro-config\src\defaults\blacklist.js



// var sharedBlacklist = [
//   /node_modules[/\\]react[/\\]dist[/\\].*/,
//   /website\/node_modules\/.*/,
//   /heapCapture\/bundle\.js/,
//   /.*\/__tests__\/.*/
// ];


var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/

];
keep learning :)
............................................................................................................................

Example : #2
error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually: - react-native-firebase (to unlink run: "react-native unlink react-native-firebase"

solutions -

Create a react-native.config.js file in the root of your project.

Update it to something like this:
// react-native.config.js
module.exports = {
  dependencies: {
    '<dependency>': {
      platforms: {
        android: null, // disable Android platform, other platforms will still autolink
      },
    },
  },
};


in my case is look like below

module.exports = {
    dependencies: {
    'react-native-firebase': {
    platforms: {
    android: null,
    },
    },
    },
    };
    

keep learning :)
....................................................................................................

Wednesday, October 16, 2019

node_modules\@react-native-community\cli-platform-android\native_modules.gradle' line: 169



:ReactNative:Cannot run program "npx": CreateProcess error=2, ═х єфрхЄё  эрщЄш єърчрээ√щ Їрщы
:ReactNative:Automatic import of native modules failed.

FAILURE: Build failed with an exception.
* Where:
* Where:
Script 'C:\Users\sapan\Desktop\React Native\myapp\node_modules\@react-native-community\cli-platform-android\native_modules.gradle' line: 169

* What went wrong:
A problem occurred evaluating script.
> Cannot invoke method getErrorStream() on null object




Solutions
Go to -->
node_modules\@react-native-community\cli-platform-android\native_modules.gradle

"npx --quiet react-native config" to "npx.cmd --quiet react-native config" 

















Tuesday, October 1, 2019

FORMIK

FORMIK

install two lib
yarn add formik yup

...................................................................................................................................................................................................................................
Step: #1
import React from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import * as Yup from 'yup'

const loginSchema = Yup.object().shape({
    email: Yup.string()
        .email('Invalid Email')
        .required('The email is required.'),
    password: Yup.string().required('The password is required.')

})

Step: #1.1
<Formik
                initialValues={{
                    email: '',
                    password: ''
                }}
                validationSchema={loginSchema}
                onSubmit={(values, { setSubmitting }) => {
                    console.log(values)
                }}
            >
</Formik>




Step: #1.2
             <Form>
                        <Field type="email" name='email' />
                        <ErrorMessage name='email' />

                        <Field type="password" name='password' />
                        <ErrorMessage name='password' />
                        <button type='submit'>Submit</button>
                    </Form>


....................................................................................................................................................................................................................................
Step: #2 [FINAL CODE]

import React from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import * as Yup from 'yup'

const loginSchema = Yup.object().shape({
    email: Yup.string()
        .email('Invalid Email')
        .required('The email is required.'),
    password: Yup.string().required('The password is required.')

})
const Login = () => {
    return (
        <div>
            <Formik
                initialValues={{
                    email: '',
                    password: ''
                }}
                validationSchema={loginSchema}
                onSubmit={(values, { setSubmitting }) => {
                    console.log(values)
                }}
            >
                {({ isSubmitting, isValid }) => (
                    <Form>
                        <Field type="email" name='email' />
                        <ErrorMessage name='email' />

                        <Field type="password" name='password' />
                        <ErrorMessage name='password' />
                        <button type='submit'>Submit</button>
                    </Form>
                )}
            </Formik>
        </div>
    )
}

const App = () => {
    return (
        <>
            <Login />
        </>
    )
}

export default App
...................................................................................................................................................................................................................................
Example: #3   [ CONFIRM PASSWORD]
import React from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import * as Yup from 'yup'

const loginSchema = Yup.object().shape({
    firstName: Yup.string()
        .required('Your First name is required!')
        .min(3, 'Too short')
        .max(257, 'Too long'),

    email: Yup.string()
        .email('Invalid Email')
        .required('The email is required!.'),

    password: Yup.string().required('The password is required!.'),

    confirmPassword:Yup.string()
        .oneOf([Yup.ref('password'), null], `password doesn't match`)
        .required('you need to confirm your password')

})
const Input = ({ field, form: { touched, errors }, ...props }) => {
    return <input {...field} {...props} />
}

const Login = () => {
    return (
        <div>
            <Formik
                initialValues={{
                    firstName: '',
                    email: '',
                    password: ''
                }}
                validationSchema={loginSchema}
                onSubmit={(values, { setSubmitting }) => {
                    console.log(values)
                }}
            >
                {({ isSubmitting, isValid }) => (
                    <Form>
                        <Field type="text" name='firstName'
                            component={Input} />
                        <ErrorMessage name='firstName' />

                        <Field type="email" name='email'
                            component={Input} />
                        <ErrorMessage name='email' />

                        <Field type="password" name='password'
                            component={Input} />
                        <ErrorMessage name='password' />

                        <Field type="password" name='confirmPassword'
                            component={Input} />
                        <ErrorMessage name='confirmPassword' />

                        <button type='submit'>Submit</button>
                    </Form>
                )}
            </Formik>

        </div>
    )
}
const App = () => {
    return (
        <>
            <Login />
        </>
    )
}
export default App


...................................................................................................................................................................................................................................
Step: #4


...................................................................................................................................................................................................................................
Step: #5


Monday, September 30, 2019

useEffect

import React, { useState, useEffect } from 'react'

const App = () => {
    const [countries, setCountries] = useState([])

    useEffect(() => {
        const getCountries = async () => {
            const response = await fetch('https://restcountries.eu/rest/v2/all?fields=name')
            const responseJson = await response.json()
            console.log(responseJson)
            setCountries(responseJson)
        }
        getCountries()
    }, [])

    return (
        <div>
            <ul>
                {countries.map((country, index) => {
                    return (
                        <li key={index}>
                            {country.name}
                        </li>
                    )
                })}
            </ul>

        </div>
    )
}

export default App

Friday, September 27, 2019

localStorage and sessionStorage To Store Data

localStorage and sessionStorage To Store Data
....................................................................................................................................................................................................................................
LocalStorage

import React, { Component } from 'react'
class App extends Component {

  setData() {
    let obj = { name: 'Sapan', password: 123333, email: 'my@gmail.com' }
    localStorage.setItem('mysetData', JSON.stringify(obj))
  }
  
  getData() {
    let data = localStorage.getItem('mysetData')
    data = JSON.parse(data)
    console.log(data)
   console.log(data.email)
  }

  render() {
    return (
      <div>
        <h1>Hello</h1>
        <button onClick={() => this.setData()}>setData</button>
        <button onClick={() => this.getData()}>getData</button>
      </div>
    )
  }
}

export default App

................................................................................................................................................................................................................................
SessionStorage

import React, { Component } from 'react'
class App extends Component {

  setData() {
    let obj = { name: 'Sapan', password: 123333, email: 'my@gmail.com' }
    sessionStorage.setItem('mysetDatasession', JSON.stringify(obj))
  }

  getData() {
    let data = sessionStorage.getItem('mysetDatasession')
    data = JSON.parse(data)
    console.log(data)
    console.log(data.email)
    console.log(data.name)
  }

  render() {
    return (
      <div>
        <h1>Hello</h1>
        <button onClick={() => this.setData()}>setData</button>
        <button onClick={() => this.getData()}>getData</button>
      </div>
    )
  }
}

export default App







Wednesday, September 25, 2019

React native app optimization or Performance && clean

React native app optimization or Performance.









How to clear react native cache?


How to reset iOS Simulator or Erase all simulator data ?
To reset the iOS simulator and erase all simulator data go to menu and Hardware -> Erase All Content and Settings


How to clean iOS build ?
To clean the iOS build press Option+Shift+Command+K or go to Xcode menu Product -> Clean Build Folder.
This will only clean cache for your current target.


How to clean Android Build Cache
Go to root directly of your react native project and run following commands:
cd android && ./gradlew cleanBuildCache
or
cd android && gradlew cleanBuildCache


Happy Cleaning !!

.............................................................................................................................................................................................................................
 Memory Issues
The Problem

Memory leaks are one of the main problems, particularly for Android apps built on React Native because of many unnecessary background processes.

You can find leaks using XCode as follows:

a. Navigate to XCode > Product > Profile
b. Choose Leaks

You can find memory leaks using Android Studio as follows:

a. Start your React Native app normally
b. Run Android Studio
c. Navigate to Tools > Android > Enable ADB Integration
d. Click on Tools > Android > Android Device Monitor
e. After the Android Device Monitor starts, click on Monitor > Preferences
f. Use Perf Monitor to identify any memory leaks








Navigation Project

......................................................................................................................................................................................................................................
Add.js
import React, { Component } from 'react'
import { connect } from 'react-redux'

class AddProduct extends Component {
    constructor(props) {
        super(props)
        this.state = {
            id: '',
            name: '',
            price: ''
        }
    }
handelTextInput=(e)=>{
    this.setState({
        [e.target.name]: e.target.value
    })
}

onSubmit=(e)=>{
    e.preventDefault()
    this.props.dispatch({
        type: 'ADD_PRODUCT',
        sapan: this.state
    })
 
    this.props.history.push('/')
}
    render() {
        return (
            <>
                <h1>Add Product</h1>
                <form onSubmit={this.onSubmit}>
                    <input type='text' name='id' value={this.state.id}  onChange={this.handelTextInput} /><br></br><br></br>
                    <input type='text' name='name' value={this.state.name} onChange={this.handelTextInput} /><br></br><br></br>
                    <input type='text' name='price' value={this.state.price} onChange={this.handelTextInput} /> <br></br><br></br>
                   <button type='submit'>Save</button>
                </form>
            </>
        )
    }
}

export default connect()(AddProduct)
....................................................................................................................................................................................................................................
Edit.js

import React, { Component } from 'react'
import { connect } from 'react-redux'

class EditProduct extends Component {


onSubmit=(e)=>{
    e.preventDefault()
    this.props.dispatch({
        type: 'UP_PRODUCT',
        product: {
            id: e.target.id.value,
            name: e.target.name.value,
            price: e.target.price.value
        }
    })
 
    this.props.history.push('/')
}

    render() {
        return (
            <>
                <h1>Edit Product</h1>
                <form onSubmit={this.onSubmit}>
                    <input type='text' name='id' readOnly={true} defaultValue={this.props.product.id}/>
                    <input type='text' name='name' defaultValue={this.props.product.name} />

                    <input type='text' name='price' defaultValue={this.props.product.price} />
                    <input type='submit' value='Save'/>
                </form>
            </>
        )
    }
}
const mapStateToProps=(state)=>{
    return{
        product:state.products[0]
    }
}

export default connect(mapStateToProps)(EditProduct)

..........................................................................................................................................................................................................................
List.js

import React, { Component } from 'react'
import { connect } from 'react-redux'


class ListProduct extends Component {
    Edit=(e)=>{
        var id = e.target.getAttribute('data-id')
        this.props.dispatch({
            type:'EDIT_PRODUCT',
            id:id
        })
        this.props.history.push('/edit/'+ id)

    }

    Delete=(e)=>{
        var id = e.target.getAttribute('data-id')
        alert(id)
        this.props.dispatch({
            type:'DELETE_PRODUCT',
            id:id
        })
        this.props.history.push('/')
    }
    render() {
        return (
            <>
                <h1>List Product</h1>
                <table border='2'>
                    <thead>
                        <tr>
                            <th>id</th>
                            <th>name</th>
                            <th>price</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.props.product.map((sapan, index)=>{
                            return(
                                <tr key={index}>
                                    <td>{sapan.id}</td>
                                    <td>{sapan.name}</td>
                                    <td>{sapan.price}</td>
                                    <td>
                                        <input type='button' value='Edit' data-id={sapan.id} onClick={this.Edit}/>
     
                                        <input type='button' value='Delete' data-id={sapan.id} onClick={this.Delete}/>
                                        </td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table>

            </>
        )
    }
}
const mapStateToProps=(state)=>{
    return{
        product:state.products
    }
}
export default connect(mapStateToProps)(ListProduct)
......................................................................................................................................................................................................................
reducers
reducer.js

const initialState = {
    products: []
}

const productReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'ADD_PRODUCT':
            return {
                ...state,
                products:state.products.concat([action.M])
            }
            case'DELETE_PRODUCT':
            return{
                ...state,
                products: state.products.filter((p)=>p.id !==action.id)
            }
            case 'EDIT_PRODUCT':
                return{
                    ...state,
                    products: state.products.filter((p)=>p.id ===action.id)
                }
                case 'UP_PRODUCT':
                    var pro =state.products.map((p)=>{
                        if(p.id === action.product.id){
                            return{
                                ...p,
                                id:action.product.id,
                                name: action.product.name,
                                price: action.product.price
                            }
                        }
                        else {
                            return p
                        }
                    })
                    return{
                        ...state,
                        products: pro
                    }
        default:
            return state

    }

}

export default  productReducer

..................................................................................................................................................................................................................

App.js
import React, { Component } from 'react'
import { BrowserRouter, Link, Route, Switch } from 'react-router-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import productReducer from './reducers/reducers'

import ListProduct from './products/List'
import AddProduct from './products/Add'
import EditProduct from './products/Edit'

const store = createStore(productReducer)

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <BrowserRouter>
          <Link to="/">Home | </Link>
          <Link to="/add"> Add | </Link>
          <Link to="/edit/:id">Edit | </Link>
          <Switch>
            <Route path="/" exact strict component={ListProduct} />
            <Route path="/add" exact component={AddProduct} />
            <Route path="/edit/:id" exact component={EditProduct} />
          </Switch>
        </BrowserRouter >
      </Provider>

    )
  }
}










Thursday, August 29, 2019

Facebook Login

keytool -exportcert -alias androiddebugkey -keystore android/app/debug.keystore | openssl sha1 -binary | openssl base64

or
Facebook Key hash

Step 1 - Download openssl from the link given bellow
step 2 - Select file according to your system.
After finished download extract the downloaded file.

step -3 create a folder in C drive named 'openssl'

copy the all file from the extracted folder and past it in
openssl folder you just created.
example C:/openssl

step 4 - Go to system search box and type 'cmd'

Past this code in command prompt windows.

"keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | C:\openssl\bin\openssl.exe sha1 -binary | C:\openssl\bin\openssl.exe base64"

step 5 - hit Enter.

it will asked for password, now type 'android' as password
and hit Enter again.

THis process will generate a 27 digi key hash copy the hash including =sign

note it key -alias ==>androiddebugkey
.......................................................................................................................................................................................................................................
Example : #1 [React Native Tutorial: Facebook Login Example]
Step: #1.1

Setup a Facebook App





..................................................................................................................................................................................................................................
Step: #1.2



..................................................................................................................................................................................................................................
Step: #1.3


..................................................................................................................................................................................................................................
Step: #1.4
Click the Facebook Login Set up button.






..................................................................................................................................................................................................................................
Step: #1.5

..................................................................................................................................................................................................................................

Step: #1.6




..................................................................................................................................................................................................................................
Step: #1.7
we need to create a Key Hashes. To get the key hashes.

https://code.google.com/archive/p/openssl-for-windows/downloads

- download and Extract it, and also set the path of  bin  looks like [C:\Users\sapan\Downloads\openssl-0.9.8k_X64\bin]
- open a command prompt and copy and paste the below command.

keytool -exportcert -alias androiddebugkey -keystore android/app/debug.keystore | openssl sha1 -binary | openssl base64







..................................................................................................................................................................................................................................

Step: #1.8


..................................................................................................................................................................................................................................

Step: #1.9

android/app/res/values/strings.xml then add this value.






..................................................................................................................................................................................................................................
Step: #1.10


..................................................................................................................................................................................................................................

Step: #1.11




Step: #1
 https://console.firebase.google.com/?gclid=Cj0KCQjwz8bsBRC6ARIsAEyNnvqj5Reg9euAdO1kRWEZ3n3h0Kd3upZgIgbeF6aRSOe5noO9-QpMJm4aAo6OEALw_wcB




Step: #2




Step: #3





Step: #4




Step: #5






Step: #6
Enable Email and password




Step: #7





Step: #8



Step: #9




Step: #10



Step: #11

Step: #12

Step: #13




Step: #14
. firebase install
    yarn ad firebase






Step: #15

Step: #16

Step: #17

Step: #18
Step: #19
Step: #20