A Tutorial on Firebase Hosting
Strategy

A Tutorial on Firebase Hosting


If you are looking to host your NextGen web app safely, Firebase from Google can put you at ease by providing fast, reliable, and secure static hosting for your web app. Offering production-grade web content hosting, Google Firebase enables you to effortlessly deploy web apps and static web page content and connect to a CDN (content-delivery network) with a single command.

Furthermore, with Firebase as an all-in-one hosting solution, you are exempt from sizing up various available cloud-based hosting service providers.

The prerequisites you need to do to get started with Firebase hosting are:

  • The latest version of Node.js.
  • An uninterrupted Data connection.
  • A Google Firebase account

Features That Make Firebase a Reliable Choice

Content Security

Firebase hosting is served over a secure connection. It has a built-in SSL, which requires no further configuration, ensuring that content is always delivered with uncompromised security standards at any point intime.

Speedy Content Delivery

Since each file you upload is on SSDs, cached at CDN edges, you can be sure your web app content is delivered fast to users around the world.

Quick Deployment

Firebase comes with a CLI, which deploys your app in a few seconds. With the CLI, you can easily upload your files from a local directory to the hosting server and add deployment targets into your build process.

One-Click Roll Backs

Any mistakes or error made during the hosting process is reversable, as Firebase Hosting enables you to manage the full version and release with one-click rollbacks.

How Does it Work?

Built with the idea of modern web development, Firebase makes deploying a simple landing page or a scalable and complex web app quite simple. Successful hosting gives your app the feel-good features, defined infrastructure, and incredible tools designed to manage static websites.

With Firebase CLI, you are able to deploy files from local directory to hosting server that has SSL configuration on global CDN. The project is given a sub-domain of firebaseapp.com. Its lightweight configuration options enable you to build sophisticated progressive web apps. Developers can easily rewrite URLs or set-up custom headers.

When a site is ready for production, you can connect your own domain name to Google Firebase Hosting and also get an SSL certificate for enhanced content security.

Why Leverage Firebase Hosting?

For business-grade apps, it is important to choose a robust, scalable, and flexible framework for web application development. Firebase promises an integrated platform for dynamic mobile apps. Some of its pros are:

1. Competitive Analytics

Google Firebase comes with a free analytics dashboard that has innovative qualities and the capacity to report up to as many as 500 event types. Due to its ability to provide you with crystal clear insights for understanding user behavior, it is easy to optimize your application for better performance, scalability, and personalization. Some of the crucial features of Firebase analytics are:

  • Streamlined segmentation of users.
  • Unlimited reporting.
  • Integration with other essential services.

2. High-Quality and Interactive Applications

With Firebase, developers can enjoy ample space to create unique, interactive, and high-quality apps using its incredible features and functions. Some of the remarkable, innovative features of Google Firebase are:

  • Authentication.
  • Crash reporting.
  • Storage and data syncing.
  • Remote configuring.
  • Real-time database.
  • Cloud messaging.
  • Test Lab.

With these features, you can store, sync, add, and integrate important data in real-time, which in turn makes a user’s experience even more gratifying.

3. App Marketing Feature: Invites

After developing your business-focused app, you can walk an extra mile to compel users to consider and install your app. Firebase contains a feature called “invites,” which enables word-of-mouth advertising. Invites empower your marketing efforts by sending personalized invitations messages and email to prospects and existing clients.

4. Better User engagement

You definitely want your app to do well and impress users with its scalable features and secure usage. Some of the built-in features of Google Firebase that satisfy this purpose for you are:

  • App indexing.
  • Dynamic links.
  • Real-time Notifications.

Getting Started

Install the Firebase CLI

To install Firebase hosting, the CLI requires you to first install Node.js (version 5.10.0 or greater) and npm. To install them both, follow the instructions given on https://nodejs.org/.

After getting Node.js and npm installed, you can go ahead and install the Firebase CLI via npm:

 npm install -g firebase-tools

Then, you can re-run the above command in order to update to the latest version.

Initialize Your App

If you have your Firebase app ready to deploy, you can go inside the project directory to run the command:

 firebase init

This action creates a firebase.json settings file in the root of your project directory.

Add a File

After initializing your application, you will be asked to use the directory as the public root by default. This is helpful when you don’t have a valid index.html file in your public root directory.

Deploy Your Website

At this stage, you are able to deploy your website, which you can do by running:

 firebase deploy 

In the end, you will see your app deployed at the domain <YOUR-FIREBASE-APP>.firebaseapp.com.

Manage and Rollback Deploys

From the Hosting panel in the Firebase Console, you can see a full history of your deploys. To roll back to a previous deploy, hover over its entry in the list, click the overflow menu icon, and then click Rollback.

Now, your app is ready to share with the world! Next up, check out how to customize hosting behavior, connect a custom domain, or take a look at the full documentation for the Firebase CLI.

Further Reading



Source link

Worker Threads: Node Parallelism - DZone Web Dev
Strategy

Worker Threads: Node Parallelism – DZone Web Dev


Concurrency vs Parallelism

Node.js has long excelled at concurrency. With the recent release of Node 13.0, Node now has a stable answer to parallelism as well. 

Concurrency can be thought of as switching between async processes, which all take turns executing, and, while idle, return control back to the event loop. On the other hand, parallelism is the ability for a process to separate and run simultaneously on multiple threads. There are other solutions in JavaScript that have tried to address this problem. For an in-depth comparison, I found this article useful.

The Master Script

The master script must do 3 things

  1. Create the workers by referencing the js file for the worker. 
        const worker = new WorkerThread.Worker(join(__dirname, './worker.js'))
  2. Send messages to the workers initiating work. A message is just a JavaScript object, so if you need to customize the behavior of the worker, you can include any categorization, data, etc.
  3.     worker.postMessage({foo:"stuff"});
  4. Register responses to the actions. Any response from the worker will be a message event, returning an object. You could return a string or a more complex object with the results of whatever operations the worker has performed. 
  5.     worker.on('message', (message) => { // do stuff with the response }
    

You may also like: Parallelism and Concurrency in Python.

Now, try combining those together into a script

const { join } = require('path');
const WorkerThread = require('worker_threads');

const THREAD_COUNT = 30;

/**
 * before running Modify THREAD_COUNT
 */
(async () => {

  // Setup whatever data needed to run your jobs. 
  const users = await getAllUsers();

  // Define functions to handle the different messages passed by the workers
  function handleStatusReport(workerNumber, report) {
    console.log(`the worker:${workerNumber} says`, report.body || report);
  }

  function handleWorkerFinished(worker, workerNumber, message) {
    console.log(`done with ${JSON.stringify(message.body)}!`);
    if (i < users.length) {
      worker.postMessage(users[i]);
      i += 1;
    } else {
      console.log(`Worker number ${workerNumber} completed working!`);
    }
  }

  //Spin up our initial batch of workers... we will reuse these workers by sending more work as they finish
  for (let j = 0; j < Math.min(THREAD_COUNT, users.length); j += 1) {
    const worker = new WorkerThread.Worker(join(__dirname, './worker.js'));
    console.log(`Running ${i} of ${users.length}`);
    worker.postMessage(users[i]);
    i += 1;

    //Listen on messages from the worker
    worker.on('message', (messageBody) => {
      //Switch on values in message body, to support different types of message
      if (messageBody.type === 'done') {
        handleWorkerFinished(worker, j, messageBody);
      } else {
        handleStatusReport(j, messageBody);
      }
    });
  }
})();

The Worker Script

The worker can as simple as 

parentPort.on('message', async someObject => // Some function that uses the object, and can report back to the parent worker by  );

The worker is not required to report back to the master; however, this is good practice to know whether or not the worker finished, failed, or, optionally, to return the results of the calculations.

  parentPort.postMessage({ type: 'done', body: {key: 'value'} });
  parentPort.postMessage({ type: 'log', body: {message: 'something happened'} });

The examples above have a property type with values done and log. Both the name and values are arbitrary — just remember that you can exchange data between the workers and the master in this fashion. Additionally, I should note that sending a message from the worker to the master will not terminate the worker. So, one worker can send many messages during its execution.

Here is a more thorough template for a worker:

const { parentPort } = require('worker_threads');

async function process(someObject) {
  //Do lots of processing here...

  //Send a status update to the PRIMARY
  parentPort.postMessage({ type: 'status', body: 'still working' });

  //Do more processing...

  //Send final message with relevant data back to the PRIMARY script
  parentPort.postMessage({ type: 'done', body: {key: 'value'} });
}

//Register method to execute on message
parentPort.on('message', async someObject => process(someObject));

Additional Notes

Thread Workers have only recently become a stable feature in Node 13.0. If any error occurs while running older versions of node, it is worth making sure thread workers are enabled by running with the –experimental-worker flag. 

node --experimental-worker master.js

Further Reading



Source link

Strategy

Highlights of the HTTP Archive Web Almanac


I spent my Sunday reading the HTTP archive web almanac and shared the surprising and interesting pieces in a Twitter thread. I like to own my data – so here we have the thread on my own site. Enjoy!


Spending my Sunday morning reading the Web Almanac sharing internet stats and analyzing HTTP Archive data for 2019.

I’ll share facts and stats that I think are interesting in a thread. 👇 🙂

#

Only ~80% of sites compress their JavaScript files. 😲

Chart showing how many sites compress their JavaScript files using gzip (~65%) or brotli (~15%)

Source

Edited: I tweeted initially that it’s 65% because I missed the fact that gzip and brotli should count together. 🙈

#

jQuery still powers 85% of the crawled sites

It always feels like React/Vue/Angular are all over the internet – they’re not… jQuery still powers 85% of the crawled sites. 😲

Table showing the usage of libraries – jQuery is on first position with being included on 85% of the crawled sites

Source

#

React powers 5% of the crawled sites

The numbers for sites using “cutting-edge” frameworks are relatively low with React being the most popular with ~5% on desktop.

Distribution showing how many sites are using React, Angular or others. Only ~5% of sites use react.

Source

#

ES modules are barely used

Even though the ES Module support is quite good these days they are not really used.

~1% is surprisingly low because you can use a fallback strategy shipping a single bundle using the `nomodule` attribute and use modules for supporting browsers today.

Chart showing the usage of ES Modules. Only roughly 1% of crawled sites use modules

Source

#

Low usage of source maps in production

Only ~20% of sites use source maps? 😲

Chart showing the usage of source maps – roughly 20%

Source

#

CSS flexbox and grid usage

Roughly 50% of sites use flexbox – only 2% use grid.

Chart showing that 50% of crawled sites use flexbox

Graphic showing that only 2% use CSS grid

Source

#

The highest found z-index value

incredible high z-index value with dozens of 9s and an !important

Source

#

Usage of responsive images

Only 20% of sites make use of responsive images…

Chart showing the usage of responsive image markup: `sizes` 18%, `srcset` 21% and the picture element 2% usage

Source

#

Usage of the alt attribute on images

No surprise here, but yeah… image alt attributes are not used as much as they should. :/

Paragraph from the almanac highlighting the following sentence: Only 39% of images use alt text that is longer than six characters.

Source

Edited: As Boris Schapira pointed out, images can be hidden from assistive technology by providing an empty alt attribute (alt=""). This fact was not taken into consideration by the Almanac and makes the statistic meaningless.

26% of the pages use font-display. 😲 That’s surprisingly high in my opinion. Because the support is not super-duper yet. I wonder how big google fonts’ influence is in this trend. 🙈

Graphic: 26% of pages use font-display

Source

Honestly, I expected fewer sites being served over a secure connection. 80% of sites ship with https these days.

Chart showing that 80% of sites are served via HTTPS (mobile and desktop)

Source

12 – 14% of sites use HSTS to ensure they are only accessible by supporting browsers via HTTPS. This is also higher then I expected. 😲

Table showing the usage of HSTS: 12 (mobile) / 14 (desktop) percent use the `max-age` directive, 3 percent use `include-subdomains` and 2 percent use `preload`

Source

I got this statistic by myself recently, but it’s still sooooo low. 😿

Only roughly 5% of crawled sites use Content-Security-Policy (CSP).

Paragraph from the article: We find that only 5.51% of desktop pages include a CSP and only 4.73% of mobile pages include a CSP, likely due to the complexity of deployment.

Source

#

The state of contrast issues

4 of 5 sites ship with color contrast issues. I really wish that we get better at this. :/

Paragraph of the article: Only 22.04% of sites gave all of their text sufficient color contrast. Or in other words: 4 out of every 5 sites have text which easily blends into the background, making it unreadable

Source

#

The often missing language attribute

26% of the pages don’t specify the language of their content. This can trouble text-to-speech technology like screenreaders.

Paragraph of the article: Of the pages analyzed, 26.13% do not specify a language with the lang attribute.

Source

4 of 5 forms don’t ship with labels for their input elements. :/ I’m used to these bad numbers, but well… filling out forms can be tough for everybody (even tech people), we really have to get better at this. :/

Paragraph of the article with highlighted text: Sadly, only 22.33% of pages provide labels for all their form inputs, meaning 4 out of every 5 pages have forms that may be very difficult to fill out.

Source

10% of sites ship without headings at all. 😲

Paragraph of the article with highlighted text: Despite the importance of headings, 10.67% of pages have no heading tags at all.

Source

#

Too short title elements

Google shows 50-60 characters in their search results. Generally speaking, the used title length is not optimal across the web. (at least for google)

Graph showing the distribution of title length: median value shows 20 characters for the title and 10 characters on the 25 percentile

Source

#

Service worker adoption

Service workers are mainstream, right? 🙈 Not really… Only 0.44% of the crawled sites register a service worker.

Graphic showing that 0.44% of the crawled sites register a service worker

Source

#

The jumpy state of websites

How often do we click the wrong thing because something moved around? Too often.. Jumpy pages are the standard… :/

2 of 3 pages have a huge content shift while loading.

CLS stands for Cumulative Layout Shift – more info.

Paragraph of the article: Nearly two out of every three sites (65.32%) have medium or large CLS (Cumulative Layout Shift) for 50% or more of all user experiences.

Source

#

Big enough touch targets

Speaking about tapping the wrong thing. Only 34% of the pages include big enough buttons and links…

Graphic showing sufficient tap targets... With explanation: As of now, 34.43% of sites have sufficiently sized tap targets. So we have quite a ways to go until 'fat fingering' is a thing of the past

Source

#

WordPress’ CMS domination

WordPress usage is still massive. 75% of sites using a CMS are running on wordpress.

Graphic showing CMS distribution: WordPress is on top with 75% followed by Drupal and Joomla (both below 10%)

Source

#

Page weight and number of requests of CMS sites

CMS pages are heavy and make many requests… I did WordPress development in the past and that makes sense thinking of the audience and users of e.g. wordpress. “Just install another plugin”…

Resource consumption of CMS sites: median page weight is 2.3mb and median request count is ~85

Source

HTML is mainly served from its origin server (80%). Most used CDN is cloudflare (10%). 😲

Distribution of CDN usage for HTML: - 80% origin - 9.61% cloudflare - 5.54% google

Source

I thought the median value for page weight would be higher these days. 😀 On desktop it’s 1.9MB and on mobile, it’s 1.7MB. It’s still fairly high though imo. 🙈 (and median is clearly only one piece of the puzzle)

Tables showing the distribution of page weight across mobile and desktop: - median page weight for desktop is 1.9MB and for mobile it's 1.7MB - 90 percentile for page weight is for desktop 6.9MB and for mobile it's 6.2MB

Source


And that’s it. I highly recommend to check it out! It’s a very fascinating and interesting read about the state of the internet. 🙂





Source link

Optional Arguments MUST Use Keywords (Python3)
Strategy

Optional Arguments MUST Use Keywords (Python3)


Imagine that you are developing software for a big shipping company (why would you imagine a small one anyway), and you got a task to create a function for calculating a charge for ships based on their cargo weight. Easy breezy:

WEIGHT_RATES = [
    ( 10, 10.55),
    (  5, 5.05),
    (  2, 3.35),
    (  0, 1.25)
]

def shipping_charge(weight):
    if weight < 0:
        raise ValueError("Can't calculate shipping charge of negative weights")
    for min_weight, rate in WEIGHT_RATES:
        if weight > min_weight:
            return weight * rate

Simple enough.

But then, one day, your program eventually is going to work in another country, say the USA. One problem arises: we need to use pounds instead of kilograms for charging. No problem, here you are:

def shipping_charge(weight, pnds):
    if pnds:
       weight /= 2.2
    if weight < 0:
       raise ValueError("Can't calculate shipping charge of negative weights")
    for min_weight, rate in WEIGHT_RATES:
        if weight > min_weight:
            return weight * rate

This is getting complicated, but then one more requirement — you need to raise an exception if weight exceeds 1,000 kilograms for specific directions:

def shipping_charge(weight, pnds, exceed):
    if pnds:
       weight /= 2.2
    if exceed and weight > 1000:
       raise Exception("Weight can't exceed 1000 kg")
    if weight < 0:
       raise ValueError("Can't calculate shipping charge of negative weights")
    for min_weight, rate in WEIGHT_RATES:
        if weight > min_weight:
            return weight * rate

You may also like: 10 Reasons to Learn Python in 2019.

Do you see the problem? In this example, you came up to function with three positional arguments, two of them with the same type. The end-user, or you as a developer, can easily forget which one needs to come first and can mess them up. Due to the same type, the program will not fail, and you will get a logic error:

shipping_charge(2000, True, False)

or

shipping_charge(2000, False, True)

You can add keyword arguments with default values. This is good practice:

def shipping_charge(weight, pnds=False, exceed=False):
    if pnds:
       weight /= 2.2
    if exceed and weight > 1000:
       raise Exception("Weight can't exceed 1000 kg")
    if weight < 0:
       raise ValueError("Can't calculate shipping charge of negative weights")
    for min_weight, rate in WEIGHT_RATES:
        if weight > min_weight:
            return weight * rate

But, the problem is not solved. To resolve this issue, you need to add one star in the argument list:

def shipping_charge(weight, *, pnds=False, exceed=False):
    if pnds:
       weight /= 2.2
    if exceed and weight > 1000:
       raise Exception("Weight can't exceed 1000 kg")
    if weight < 0:
       raise ValueError("Can't calculate shipping charge of negative weights")
    for min_weight, rate in WEIGHT_RATES:
        if weight > min_weight:
            return weight * rate

That’s it, the next time you call this function, you will get an error:

>>>shipping_charge(2000, True, False)
TypeError: shipping_charge() takes 1 positional argument but 3 were given

More info: PEP-3102.


Thank you for reading!

Any questions? Leave your comment below to start fantastic discussions!

Check out my blog or come to say hi on Twitter or subscribe to my telegram channel.

Plan your best!

Further Reading





Source link

Image title
Strategy

Developing and Deploying ASP.NET Core and Entity Framework C…


Image title

This post will explain an end-to-end ASP.NET Core development and deployment to Azure. Below, we’ve provided some introductory steps to get started. A video tutorial at the end of the article will then walk you through the rest of the process. 

Clone the Sample Application

In the terminal window, cd to a working directory. Run the following commands to clone the sample app:

git clone https://github.com/azure-samples/dotnetcore-sqldb-tutorial

cd dotnetcore-sqldb-tutorial

The sample project contains a basic CRUD (create-read-update-delete) app using Entity Framework Core.

Run the Application

Run the following commands to install the required packages, run database migrations, and start the application.

dotnet restore

dotnet ef database update

dotnet run

Navigate to http://localhost:5000 in a browser. Select the Create New link, and create a couple to-do items.

Azure Cloud Shell

To run the code in Azure Cloud Shell:

Start the Cloud Shell. Select the Copy button on a code block to copy the code. Paste the code into the Cloud Shell session. Select Enter to run the code.

Create a Production SQL Database

In this step, you will create a SQL Database in Azure. When your app is deployed to Azure, it uses this cloud database.

For SQL Database, this tutorial uses an Azure SQL Database.

Create a Resource Group

See the rest of the steps in the video:



Source link

apollo-theatre-sign
Strategy

Integrate a React Native app with GraphQL and Apollo Client


apollo-theatre-sign

Are you interested in building a React Native app that uses GraphQL API endpoints? Then you should read this tutorial. You are going to learn how to leverage Apollo to build a client-side GraphQL application with React Native and Expo.

Apollo has an entire ecosystem to build GraphQL applications. You can use it to develop client-side and server-side apps separately. Apollo has more features and support than its open source competitors in GraphQL for the JavaScript world.

Getting Started

To start, create a new React Native app using the following command:

npx expo init expo-apollo-demo

# after the project directory is generated
cd expo-apollo-demo

Now, let’s install all the npm dependencies that are going to be used in this demo app. You will learn about each individual dependency whenever necessary in the rest of the tutorial. Do note that some of these dependencies are peer dependencies, and you might not use them directly.

yarn add apollo-client apollo-cache-inmemory graphql-tag apollo-link-rest apollo-link graphql graphql-anywhere qs

You may also like: Why and When to Use GraphQL.

After all the dependencies are installed, let’s add a header component inside App.js file and replace the rest of the contents that come by default with the Expo app.

//App.js
import React, { Component } from 'react'
import { StyleSheet, Text, View } from 'react-native'

class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerText}>Headlines App</Text>
        </View>
        <View style={styles.contentContainer}>
          <Text>Open up App.js to start working on your app!</Text>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  },
  header: {
    marginTop: 50,
    alignItems: 'center',
    borderBottomWidth: StyleSheet.hairlineWidth
  },
  headerText: {
    marginBottom: 5,
    fontSize: 30,
    fontWeight: 'bold'
  },
  contentContainer: {
    marginTop: 30,
    alignItems: 'center',
    justifyContent: 'center'
  }
})

export default App

Just to see if everything works, go back to the terminal window and run the command yarn start to trigger the Expo client app to run. Press i if you are using an iOS simulator or a if you are using an Android emulator.

You will get the following output when the App component renders for the first time:

Initial output

Configure Apollo Client in the React Native App

Create a new file called Client.js inside src/graphql. This file is going to contain configuration regarding the Apollo client. The apollo-client package, along with apollo-cache-inmemory and apollo-link, is a fully-featured GraphQL client that can be integrated into React or React Native apps.

To start open the newly created file and import the following statements.

import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { RestLink } from 'apollo-link-rest'

The apollo-link-rest package allows you to use third-party APIs that do not have GraphQL endpoints or have REST endpoints but what you want to transmit them into GraphQL.

The API endpoint you are going to use for this tutorial is a REST endpoint and is known as News API. Make sure to get the API key by logging in here (it’s free).

Add a RestLink for the Rest API endpoint and pass headers, which is an object representing values to be sent as headers on the request. The value you need to send while requesting data from the API endpoint is the API key.

const restLink = new RestLink({
  uri: 'https://newsapi.org/v2/',
  headers: {
    Authorization: '47e036d83ccc4058b1f85362bc2be1f4'
  }
})

Next, add the following configuration with the default cache and RestLink to complete the configuration of Apollo Client.

export const client = new ApolloClient({
  link: restLink,
  cache: new InMemoryCache()
})

Making a Request to a REST Endpoint With Apollo

In this section, let us write a query to hook the Apollo Client to fetch results from the REST API endpoint. However, the query is going to be made in GraphQL query language with the help of graphql-tag.

In the src/graphql directory, create a new file called Queries.js and import graphql-tag.

import gql from 'graphql-tag`

Next, export using the template from the gql tag and add a query that is going to fetch top headlines from the News API. Using the @rest directive Apollo manges how to parse this query.

export const Headlines = gql`
  query TopHeadlines {
    headlines
      @rest(
        type: "HeadlinesPayload"
        path: "top-headlines?country=us&category=technology"
      ) {
      totalResults
      articles @type(name: "ArticlePayload") {
        title
        publishedAt
        url
        urlToImage
        source @type(name: "SourcePayload") {
          name
        }
      }
    }
  }
`

To use the query, import it inside App.js file along with the configured Apollo client by adding the following two import statements.

import { client } from './src/graphql/Client'
import { Headlines } from './src/graphql/Queries'

The query should run whenever the component is going to mount, thus, using the life-cycle method componendDidMount you can invoke the query to fetch results. For now, let us log the result in a console.log statement and see what results the endpoint provides.

The requestHeadlines() function is going to invoke the query using Apollo Client. Invoking the query is simply done adding a promise.

class App extends Component {
 componentDidMount() {
 this.requestHeadlines()
 }

 requestHeadlines = () => {
 client
 .query({
 query: Headlines
 })
 .then(response => {
 console.log('RESPONSE ==>', response)
 })
 .catch(error => {
 console.log('ERROR ==>', error)
 })
 }

With Expo client, there is an option to Debug JS remotely. It opens the console tab in browser’s developer tools and lets you see results of log statements (just like in web development).

Here is the result of the above query. When invoked, it fetches 20 headline objects in an array with all requested fields.

Fetching 20 headline objects

Adding an Activity Indicator

Take a clear look at the above image in the previous section. In the response, you will find a field called loading that tells the app that the query is done fetching the data. This can be helpful when adding an activity indicator to display the same message to the end-user in a real mobile app.

Import the ActivityIndicator component from react-native and add the following state to the App component.

import { StyleSheet, Text, View, ActivityIndicator } from 'react-native'

// ... inside App component
state = {
  loading: true
}

Next, modify the render method to show the activity indicator component when the state variable loading is true.

render() {
 const { loading } = this.state
 if (loading) {
 return (
 <View
 style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
 <ActivityIndicator size='large' />
 </View>
 )
 }

 return (
 <View style={styles.container}>
 <View style={styles.header}>
 <Text style={styles.headerText}>Headlines App</Text>
 </View>
 <View style={styles.contentContainer}>
 <Text>Open up App.js to start working on your app!</Text>
 </View>
 </View>
 )
 }

You will get the following output:

To make it stop and behave in the way the app requires, update the state of loading when the promise resolves inside the query method.

.then(response => {
 console.log('RESPONSE ==>', response)
 this.setState({ loading: response.loading })
})

Refresh the Expo client, and you will notice that after a few seconds, when the data is fetched, the loading indicator disappears and the screen UI is displayed as before.

Displaying Articles From the API

You are all set to display an individual article component that is being fetched from the API endpoint. Add another variable to the state object called articles. To render a list of data, let’s use the FlatList component from react-native.

import {
  StyleSheet,
  Text,
  View,
  ActivityIndicator,
  FlatList
} from 'react-native'

// inside the App component
state = {
  loading: true,
  // add this
  articles: []
}

Next, update the articles state with the array from the response when the promise gets resolved.

this.setState({
  loading: response.loading,
  // add this
  articles: response.data.headlines.articles
})

The FlatList component requires three attributes to render a list of data items.

  • data: an array of data which is provided by the state variable articles.
  • renderItem: that contains the JSX for each item in the data array for which let’s create a new component called Article in a separate file in the next section.
  • keyExtractor: used to extract a unique key for a given item at the specified index for which let’s use each article’s URL for that is going to be unique.

That said, modify the render function as below:

return (
  <View style={styles.container}>
    <View style={styles.header}>
      <Text style={styles.headerText}>Headlines App</Text>
    </View>
    <View style={styles.contentContainer}>
      <FlatList
        data={articles}
        renderItem={({ item }) => <Article {...item} />}
        keyExtractor={item => `${item.url}`}
      />
    </View>
  </View>
)

A little modification to the styles as well:

container: {
 flex: 1,
 backgroundColor: '#fff',
 marginBottom: 70
 },

 // ... rest remains same
contentContainer: {
 marginTop: 30,
 }

Creating the Article Component

Inside the src/components directory, create a new file called Article.js. For now, this component is going to display the title and source of each headline.

The Article component is going to be a presentation component that receives everything from the App component as props. Add the following to the file.

import React from 'react'
import { View, Text, StyleSheet } from 'react-native'

const Article = ({ title, source }) => (
  <View style={styles.content}>
    <Text style={styles.source}>{source.name}</Text>
    <Text style={styles.title}>{title}</Text>
  </View>
)

const styles = StyleSheet.create({
  content: {
    marginLeft: 10,
    flex: 1
  },
  source: {
    color: '#3d3c41',
    fontSize: 14,
    fontWeight: '500',
    marginBottom: 3
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 15
  }
})

export default Article

Why are the title and source getting destructured? This is because in the App.js file, when passing the item inside the renderItem attribute of FlatList component, you have already destructured the item using the spread operator.

renderItem={({ item }) => <Article {...item} />}

Import the Article component in App.js file for its work.

import Article from './src/components/Article'

Now, go back to the simulator in which you are running the Expo client, and you will get a similar result as the following.

Final output

Conclusion

Congratulations! You have successfully integrated an Apollo client and converted a REST endpoint to query using GraphQL query language. I hope you have fun reading this introductory tutorial that covers an important aspect of React Native development with GraphQL.

Further Reading


If you enjoyed this article and want to learn more about GraphQL, check out this collection of tutorials and articles on all things GraphQL.



Source link

google-sign-graffitti
Strategy

Guide to New JavaScript Features Introduced at Google I/O 20…


google-sign-graffitti

On May 6 and 7, 2019, the most recent Google I/O conference was held. This is an annual technology event that has been organized by Google every year since 2008. The forum brings together developers from around the world to present and discuss topics related to Google products, open Internet technologies, and new trends in the software industry.

One of the biggest trends that was covered at this event was a series of changes with JavaScript. Mathias Bynens and Sathya Gunasekaran covered many of these changes in a talk titled: “What’s new in JavaScript“. This is a great video to check out. These two men have worked on Google’s V8 JavaScript engine project, so they are very knowledgeable about the impact of these changes. However, we wanted to summarize the changes here.

You may also like: How JavaScript Actually Works: Part 1.

Recent Google Conference Highlights the Evolution of JavaScript

JavaScript is no longer a programming language that is only used to develop frontend web applications. Based on interviews with several programmers from the coworking space, JavaScript has become a powerful language and widely used for:

  • Desktop applications with Electron.

  • Multiplatform mobile applications with React Native.

According to the 2019 StackOverflow survey, JavaScript is the most popular programming language.

A number of new JavaScript features and specifications have been released. The 2019 Google I/O forum outlined all of these changes.

JavaScript Features Announced at Last Year’s Google I/O Conference

Multiple new JavaScript changes had originally been revealed in the 2018 Google I/O conference, but were not compatible with all browsers until now. In 2019, these functions are implemented in every major browser.

Iterations and Asynchronous Generator Features

Iterators can be described as pointers that sequentially run through data structure elements. These include every string, array, set, and map within these structures. The Symbol.iterator  key can be used to iterate through these features. The nextdefined method is also useful. This feature can return the properties listed below:

  • Value: This variable returns the value for the very next element in a given sequence called with the nextdefined method.

  •  Done: This Boolean variable references the secession of a sequence.

An iterator or generator can be used to asynchronously read data streams. This is very similar to the syntax of the command known as  async-await, but there are a couple of important differences.

This command will wait until the URL response has been received. After this condition is satisfied, fragments of data are released and appended to the variable. A while() function continues until the sequence is completed. You can see how these changes have made JavaScript cleaner and less detailed.

The loop-await-of continues receiving response data from the URL and the process is terminated once the stream is complete.

Finally for Your Promises

The new version of JavaScript uses the block for promises. This code is contained within the block and is executed after the promise is either rejected or resolved.

Option to Write Catch Blocks

You no longer need to pass an argument when writing a catch block.

Trimming on Various Sections of String

The trim function is most commonly used to remove white space from a string variable. However, you might not want to remove whitespace from the entire string. You can use the trimEnd and trimStart functions to delineate the parts of the string that you want to trim.

Spread Command for Objects

The spread operator will not only be available to use with arrays, but also in JavaScript objects. The spread syntax operator is valuable for object cloning.

Attributes of a Class

There are two improvements related to the attributes of a class. The first is to remove the builder function.

The constructor in the previous class is used to create an instance of the objects and assign a default value to the _country attribute. The underscore at the beginning of the variable name is a convention for declaring private attributes of the class.

However, it is only a convention and not something that is strictly applied. This means that anyone can access the _country property and could change the name of the destination country because the _country attribute remains publicly accessible.

Unless you make an internal change when assigning a value to the _country attribute, the function that assigns the value to the attribute previously retrieves the country name from the random function. In this way, the value cannot be assigned from the direct assignment to the instantiated object.

The syntax of classes is improved by removing class builder and directly initializing all top-level class attributes. The other significant improvement is making every private member truly private.

New Array Methods: flat and flatMap

The flat method is used to create a new array with all the elements and/or arrays that the main array may contain.

New Object.fromEntries() method

The  Object.fromEntries() method transforms a list of key-value pairs into an object. It produces a result contrary to the Object.entries() method.

With the Object.fromEntries() method, the opposite happens. That is, it converts an object into an array.

Further Reading



Source link

list-on-pavement
Strategy

Building a List With ASP.NET Core


list-on-pavement

I’ve recently been working with ASP.NET Core to build some functionality involving building a list of values. Typically, with ASP.NET  Core using Razor, you have a form that may look something like this:

@using (Html.BeginForm("MyAction", "ControllerName", FormMethod.Post)
{
    @Html.AntiForgeryToken()
    <div class="form-group">
        @Html.LabelFor(model => model.MyValue)
        @Html.TextBoxFor(model => model.MyValue)
    </div>

    <div class="form-group">
        <button type="submit">Submit</button>
    </div>

This works really well in 90% of cases, where you want the user to enter a value and submit. This is your average CRUD application; however, what happens if, for some reason, you need to manipulate one of these values? Let’s say, for example, that you want to submit a list of values.

For the sake of simplicity, we’ll say that the controller accepts a CSV, but we want to build this up before submission. You can’t simply call a controller method for two reasons: the first is that the controller will reload the page; the second is that you don’t have anywhere to put the value on the server. If this was, say, a method to create an entry in a database, the database entry, by definition, couldn’t exist until after the submission.

This all means that you would need to build this list on the client.

You may also like:
Blazor Form Validation.

A Solution

Let’s start with a very simple little feature of Html Helpers — the hidden field:

@Html.HiddenFor(model => model.MyList)

This means that we can store the value being submitted to the user, without showing it to the user.

We’ll now need to display the data being added. An easy way to do this is a very simple table. (You can load existing values into the table for editing scenarios):

    <div>
        <table id="listTable">
            <tbody>
                @if ((Model?.ValueList ?? null) != null)
                {
                    @foreach (var v in Model.ValueList)
                    {
                        <tr>
                            <td>@v</td>
                        </tr>
                    }
                }
            </tbody>
        </table>
    </div>    

Pay particular attention to the Table Id and the fact that the conditional check is inside the tbody tag. Now, let’s allow the user to add a new piece of data:

    <div class="form-group">
        @Html.LabelFor(model => model.NewValue)
        @Html.TextBoxFor(model => model.NewValue)
    </div>
    <div>
        <button type="button" id="add-value">Add Value</button>
    </div>

Okay, so now we have a button and a field to add the value; we also have a method of displaying those values. We’ll need a little bit of Javascript (JQuery in this case) to append to our list:

@section Scripts {
        $('#add-value').click(() => {

            const hiddenList = $('#MyList');
            const newValue = $('#NewValue');

            if (!hiddenList.val()) {
                hiddenList.val(newValue.val());
            } else {
                hiddenList.val(hiddenList.val() + ',' + newValue.val());
            }

            $('#listTable > tbody:last-child').append('<tr><td>' + newValue.val() + '</td></tr>');            
        });

On the button click, we get the hidden list and the new value. We then simply add the new value to the list. Finally, we manipulate the table in order to display the new value. If you F12 the page, you’ll notice that the Razor engine replaces the Html Helpers with controls that have Ids that are the same as the fields that they are displaying. (Note: that if the field name contains a “.” as in  MyClass.MyField, the Id would be MyClass_MyField).

When you now submit this, you’ll see that the hidden field contains the correct list of values.

References

Further Reading



Source link

Vue Tutorial 8 — Component Events
Strategy

Vue Tutorial 8 — Component Events


In our pursuit of being able to handle large, scalable, maintainable web apps we became familiar with and learned about Vue Components. We learned how to:

  • Define a component.
  • Instantiate a component.
  • Pass data to a component using props.

In this tutorial, we’ll learn how to trigger events in the app based on some user action registered by our “child” component. 

Component Events

As we build out the blog feature, it may become necessary for our “child” components to communicate back to the “parent” app. For example, we may decide to include a feature to vote on comments. Let’s implement this now, and we’ll start by adding a button to the user-comment component from the previous tutorial

The above component employs a template literal to allow our template to be more readable and span across multiple lines, rather than being written in a single line. 

Image title

Example output

Our most immediate problem right now is the fact that nothing happens when the thumbs up icon is pressed. Let’s fix this.

The parent app has the ability to listen to a particular event on a component:

When the component triggers a thumbs-up event, we will then call the  thumbsUp method, which we must implement in the app:

With the parent listening for a child’s thumbsUp event, we must now trigger this event on icon click. To achieve this we will emit an event using the $emit method

You may also like: How and Why We Moved to Vue.js.

Image title

Listening for thumbsUp event

As you can see, the  thumbsUp method gets triggered when the icons is pressed. We have successfully emitted an event from the child component to the parent. How about passing some data from the child to the parent? Let’s pass the comments id so the parent can know which comments should receive the new like. 

You can adjust the parents thumbsUp method to show us what’s being passed from the child

Don’t forget to pass this event, as per below code block

As you can see in the screenshot below, we now receive the id of the comment that was liked!

Image title

Notification that comment was liked

To update a comment’s number of likes, we must naturally first add that property to our comments starting with a default value of 0

Now, we can search the comments array by id and increment the number of likes

To ensure that our “Like” mechanism works, let’s display the number of likes next to the icon inside the child component

If you followed the tutorial correctly, you now have a working comment-like mechanism that looks like the following

Image title

Final output

Conclusion

In this tutorial, you’ve learned how to handle component events and how to literally “emit” them to the parent. This is a feature that I think you’ll use quite often. As a challenge, I would suggest that you also implement a dislike button that decrements the number of likes for each comment following the methods you’ve learned today. 

The code for this tutorial is available here.

Note: You can find parts onetwothreefourfivesix and seven of this series at their respective links. 

Further Reading



Source link

How to Deploy an Angular App on Firebase
Strategy

How to Deploy an Angular App on Firebase


In this article, I am going to share with you how you can deploy your Angular application on Firebase.

In case you don’t know what Firebase is, it’s a mobile and web application development and deployment platform. For more details, check out this link.

I have developed this simple frontend only (no backend) Todo App in Angular, which I am going to use to explain how simple it is to deploy your App in Firebase.

If you already have an app ready for deployment, you can follow along with me, as I am explaining these simple steps in this article.

Image title

Basic todo app

If you are interested in the source code of this app, you can get it from my GitHub repository link.

You may also like: How to Integrate React Application Using Firebase.

Create a Firebase Account

In order to deploy your app on Firebase, you must first need to have an account on the firebase website ( https://console.firebase.google.com).

The good news is that Firebase expects Google account for login, and I am sure you already have one. Otherwise, you can create one if you don’t have or you can create another Google account for Firebase if you don’t want to use an existing one.

Create a New Firebase Project

Once you are done with the account creation, now create your first Firebase project by clicking on the Add Project button. It’s a three-step process.

First, provide a unique name for your project. In my case, I have named it angular7-todo-app.

Second, enable Google analytics for this project, which is by default enabled so click on continue. Finally, configure the google analytics by selecting default account for firebase from the dropdown field and click on create project.

It will take 1-2 minutes to create the project, and that’s all you need to do on Firebase site for now in order to deploy this Todo App. Although you can do much more with Firebase, that’s not in scope for this article.

Image title

Creating Todo app in Firebase

Deploy App With Firebase Tool

Now we have all the setup needed at the Firebase site done, we are few steps away from the deployment of our app on Firebase.

Install Firebase Tools

We will require firebase tools installed on the machine for the deployment.

So open the command or bash window and navigate to your app project folder(in my case todo-app) and install firebase-tools on your machine via npm by running the following command:

npm install –g firebase-tools

Image title

Installing Firebase tools

Next, we need to login to Firebase from the command prompt/bash window by running following command:

firebase login --interactive

This will open the Firebase login in the browser for you to login so that we can work on our Firebase project from our machine using firebase tools CLI.

Image title

Firebase tools CLI

Configure Firebase Project Using Firebase-Tools

Now, in order to configure our Firebase project, we need to initialize the process in the project folder using following command:

firebase init

This will start a selection wizard with following steps in the console.

Step 1 —Select “Y” to proceed and then select the “Hosting: Configure and deploy Firebase Hosting sites” option since we want to only host our app at this moment.

Image title

Proceeding with “Y”

Image title

Hosting: Configure and deploy Firebase Hosting sites

Step 2 — Now, select “Use an existing project” option since we already created a Firebase project for this application.

Image title

Use an existing project

Step 3 — Next, select the newly created Firebase project, which, in my case is “angular7-todo-app.”

Image title

Selecting existing project

Step 4 – Type “No” to the “Configure as a single-page app” option since we will configure it by updating firebase.json file later on.

Image title

Not configuring application as SPA

The Firebase initialization wizard will create the following files in the project folder:

  • 404.html.
  • index.html.
  • .firebaserc.
  • Firebase.json.

Delete this index.html file since you might already have an index.html in your app project folder.

Now, edit this newly created firebase.json file and add the following configuration.

Note: here public key value refers to the deployment folder for the App so make sure the outputPath value in the angular.json should be docs.

This setting will redirect the request to index.html page whenever the App is refreshed.

Image title

Checking outputPath value

Build the Angular App

Now, run the following commad on the command/bash window from your app project folder to generate distributable files in the docs folder:

ng build --prod

Image title

Building applciation

Deploy the App on Firebase

Finally, deploy the app by running following command on the command/bash window from your app project folder:

firebase deploy

Image title

Deploying the app to Firebase

Now, open the hosting URL in the browser, which in this case is https://angular7-todo-app.firebaseapp.com.

Image title

Final output

I hope you enjoyed this article! Please leave questions and/or comments below.

Further Reading



Source link