Subscribe: SitePoint
http://www.sitepoint.com/blogs/feed/
Added By: Feedage Forager Feedage Grade A rated
Language: English
Tags:
api  app  application  blog  build  code  content  create  data  ddos  make  rails  react  redux  server  time  web 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: SitePoint

SitePoint



Learn CSS | HTML5 | JavaScript | Wordpress | Tutorials-Web Development | Reference | Books and More



Last Build Date: Thu, 21 Sep 2017 17:00:50 +0000

 



Building a React Universal Blog App: Implementing Flux

Thu, 21 Sep 2017 17:00:50 +0000

In the first part of this miniseries, we started digging into the world of React to see how we could use it, together with Node, to build a React Universal Blog App. In this second and last part, we'll take our blog to the next level by learning how to add and edit content. We'll also get into the real meat of how to easily scale our React Universal Blog App using React organizational concepts and the Flux pattern. Break It Down for Me As we add more pages and content to our blog, our routes file will quickly become big. Since it's one of React's guiding principles to break things up into smaller, manageable pieces, let's separate our routes into different files. Open your routes file and edit it so that it'll have the following code: // routes import React from 'react' import { Route, IndexRoute } from 'react-router' // Store import AppStore from './stores/AppStore' // Main component import App from './components/App' // Pages import Blog from './components/Pages/Blog' import Default from './components/Pages/Default' import Work from './components/Pages/Work' import NoMatch from './components/Pages/NoMatch' export default ( ) We've added a few different pages to our blog and significantly reduced the size of our routes file by breaking the pages up into separate components. Moreover, note that we've added a Store by including AppStore, which is very important for the next steps in scaling out our React application. The Store: the Single Source of Truth In the Flux pattern, the Store is a very important piece, because it acts as the single source of truth for data management. This is a crucial concept in understanding how React development works, and one of the most touted benefits of React. The beauty of this discipline is that, at any given state of our app we can access the AppStore's data and know exactly what's going on within it. There are a few key things to keep in mind if you want to build a data-driven React application: We never manipulate the DOM directly. Our UI answers to data and data live in the store If we need to change out our UI, we can go to the store and the store will create the new data state of our app. New data is fed to higher-level components, then passed down to the lower-level components through props composing the new UI, based on the new data received. With those four points, we basically have the foundation for a one-way data flow application. This also means that, at any state in our application, we can console.log(AppStore.data), and if we build our app correctly, we'll know exactly what we can expect to see. You'll experience how powerful this is for debugging as well. Now let's create a store folder called stores. Inside it, create a file called AppStore with the following content: // AppStore import { EventEmitter } from 'events' import _ from 'lodash' export default _.extend({}, EventEmitter.prototype, { // Initial data data: { ready: false, globals: {}, pages: [], item_num: 5 }, // Emit change event emitChange: function(){ this.emit('change') }, // Add change listener addChangeListener: function(callback){ this.on('change', callback) }, // Remove change listener removeChangeListener: function(callback) { this.removeListener('change', callback) } }) You can see that we've attached an event emitter. This allows us to edit data in our store, then re-render our application using AppStore.emitChange(). This is a powerful tool that should only be used in certain places in our application. Otherwise, it can be hard to understa[...]



Dealing with Asynchronous APIs in Server-rendered React

Thu, 21 Sep 2017 16:00:49 +0000

If you've ever made a basic React app page, it probably suffered from poor SEO and performance issues on slower devices. You can add back traditional server-side rendering of web pages, typically with NodeJS, but this isn't a straightforward process, especially with asynchronous APIs. The two main benefits you get from rendering your code on the server are: increased performance in load times improving the flexibility of your SEO. Remember that Google does wait for your JavaScript to load, so simple things like title content will change without issue. (I can't speak for other search engines, though, or how reliable that is.) In this post, I'll discuss getting data from asynchronous APIs when using server-rendered React code. React code has the entire structure of the app built in JavaScript. This means that, unlike traditional MVC patterns with a controller, you don't know what data you need until the app is rendered. With a framework like Create React App, you can quickly create a working app of very high quality, but it requires you to handle rendering only on the client. There's a performance issue with this, as well as an SEO/data issue, where traditional templating engines you can alter the head as you see fit. The Problem React renders synchronously for the most part, so if you don't have the data, you render a loading screen and wait for the data to come. This doesn't work so well from the server, because you don't know what you need until you've rendered, or you know what you need but you've already rendered. Check out this stock-standard render method: ReactDOM.render( , document.getElementById('root') ) Issues: It's a DOM render looking for a root element. This doesn't exist on my server, so we have to separate that. We don't have access to anything outside our main root element. We can't set Facebook tags, title, description, various SEO tags, and we don't have control over the rest of the DOM outside the element, especially the head. We're providing some state, but the server and client have different states. We need to consider how to handle that state (in this case, Redux). So I've used two libraries here, and they're pretty popular, so hopefully it carries over to the other libraries you're using. Redux: Storing state where your server and client are synced is a nightmare issue. It's very costly, and usually leads to complex bugs. On the server side, ideally, you don't want to do anything with Redux apart from just enough to get things working and rendering correctly. (You can still use it as normal; just set enough of the state to look like the client.) If you want to try, check out the various distributed systems guides as a starting point. React-Router: FYI, this is the v4 version, which is what is installed by default, but it's significantly different if you've got an older existing project. You need to make sure you handle your routing server side and client side and with v4 --- and it's very good at this. After all, what if you need to make a database call? Suddenly this becomes a big issue, because it's async and it's inside your component. Of course, this isn't a new issue: check it out on the official React repo. You have to render in order to determine what dependencies you need --- which need to be determined at runtime --- and to fetch those dependencies before serving to your client. Existing Solutions Below, I'll review the solutions that are currently on offer to solve this problem. Next Before we go anywhere, if you want production, server-side-rendered React code or universal app, Next] is where you want to go. It works, it's clean, and it's got Zeit backing it. However, it's opinionated, you have to use their toolchain, and the way they handle async data loading isn't necessarily that flexible. Check out this direct copy from the Next repo documentation: import React from 'react' export default class e[...]



How to Secure Your WordPress Site from the DDoS Attack Onslaught

Thu, 21 Sep 2017 15:30:46 +0000

This article was sponsored by Incapsula. Thank you for supporting the partners who make SitePoint possible. Distributed denial of service (DDoS) attacks are rapidly ramping in scale. They’ve been on the radar since at least 2000, and 2017 may be the year they become your biggest security concern. If you don’t have a DDoS strategy in place, it’s time to choose one. Based on current trends, industry experts predict that this may be a crisis year. That’s reflected in recent headlines like these: DDoS in 2017: Strap yourself in for a bumpy ride, The Register. DDoS attacks up 380% in Q1 2017, CIO Dive The 2017 DDoS tsunami will cost companies millions, TechRepublic Hackers take no holidays: 2017 DDoS attacks rise fivefold, SiliconANGLE Expect an increase in ransomware and DDoS attack combos in 2017, Enterprise Innovation 2017 may be crisis year for DDoS attacks, ComputerWeekly. The more popular a platform is, the more likely it will become a target for attacks, and WordPress is the most popular platform on the internet. In a previous post we outlined 48 ways to keep your WordPress site secure. By all means keep your WordPress patched and updated, but that won’t protect you from the zombie hoards. You need a targeted DDoS solution you can trust. How do DDoS attacks work? And what is the most effective way to guard your WordPress site? The Rapid Growth of the DDoS Threat DDoS attacks use your site’s bandwidth limitations against you. How many visitors can it handle at once? Too many, and it will become overwhelmed and unresponsive, just like when hundreds of customers walk into a physical shop at the same time. A DDoS attack simulates exactly that. A DDoS attack is equivalent to hundreds of thousands of fake customers converging on a traditional shop at the same time. The shop quickly becomes overwhelmed. The genuine customers cannot get in and the shop is unable to trade as it cannot serve them. (Deloitte Predictions 2017) For an online store or website, those fake visitors are often members of a botnet—a network of hundreds of thousands of compromised devices that are being controlled by a third party. Those devices may include: older PCs running less secure, unpatched operating systems like Windows XP compromised smartphones and other mobile, internet-connected devices smart devices such as thermostats, TVs, refrigerators, cameras and even light bulbs—commonly referred to as IoT (“the internet of things”) and fake IP addresses spoofed by compromised servers. Combined, these devices can send gigabits of garbage data to your server each second, and right now the scale of the onslaught is exploding. Late last year The Hacker News site reported the first 1 Tbps DDoS attack powered by 150,000 hacked IoT devices, and Deloitte predicts there will be ten similar attacks this year. Why is 2017 such a turning point? Several trends are converging to create the perfect storm: There are more IoT devices than ever, and they’re easy to incorporate into botnets. There is more bandwidth available than ever, and it can be used to spew junk data at your website. New DDoS strategies cause more damage with less bandwidth by hitting web applications, and there’s more of them than ever. Malware tools, like Mirai, are easier to use than ever, and DDoS-for-hire services are more accessible than ever, costing as little as $5. DDoS-for-hire is going to ramp up. The IoT botnets, combined with an easy money-making opportunity, will bring more of this kind of thing in 2017. Sceptical? Well, there’s already a 400,000 strong IoT zombie army for rent, using the Mirai malware. (The Register) How can you protect your site from a massive attack of unwanted visitors? Take a lesson from the nightclubs, and call in a bouncer. The key is to deal with the threat before it reaches your door. Continue reading %How to Secure Your WordPress Site from the DDoS Attack Onslaught% [...]



How to Publish Responsive Websites with Sketch and Launchpad

Thu, 21 Sep 2017 15:00:59 +0000

Anima have built two super-useful Sketch Plugins. Auto Layout helps designers create responsive layouts in Sketch, and Launchpad exports the responsive design as a near-finished HTML/CSS website with decent code quality. TL;DR — watch the video... allowfullscreen frameborder="0" height="315" src="https://www.youtube.com/embed/1gnxY6eC_78" width="560"> "Wait…another site builder? Really?" Well, Launchpad is more of an HTML/CSS exporter with some impressive features. It's not your typical WYSIWYG editor, since you're actually doing the design work in Sketch, a top-notch user interface design tool. You still need a developer who can take the 4-star code output and turn it into a 5-star website, but it will nonetheless save you huge amounts of time. Here's what Launchpad can actually do: Responsive design (if combined with Auto Layout) Videos, links and forms Font-family fallbacks Publishing, hosting and domains SEO (title, meta description, etc) Social media meta tags (Open Graph, etc) Version control Google Analytics (or similar) integration Keyboard-centric workflow (very Sketch-like!) Here's what you need to do manually, with code, afterward: Insert custom meta tags, if any Insert any Schema markup, if needed Refine the adaptive/responsive qualities, if required Code any JavaScript needed Code any backend functionality Minification and other web perf tricks Launchpad offers you the tools to build a static website, a foundation that you can build upon. It'll save you countless hours of your valuable time, but it won't take you to the finish line. This is a good thing because little code optimisations have a big impact on SEO and conversions, so these are the things you'll want to do manually. Let's learn how to use it! Make sure you've downloaded Launchpad first. Don't worry about Auto Layout, because it's automatically bundled into Launchpad now. We have Lots to cover, but I'll keep it brief! Responsive Design with Sketch and Auto Layout First, let's float a Group of layers/objects to the top-right corner of the parent container (which in this case is the Artboard itself). Open the "Pin" dropdown in the Auto Layout tab in the Inspector, and check both the top and right checkboxes (or click on the dots on the visual representation). Also, ensure that the offset (from the Artboard) is "17px" on both sides (top and right), and hit the "W" checkbox to declare the Group as having a fixed-width (otherwise, when the container/Artboard is resized, the responsive object will be squashed up as if declared as being a % of the container). For the HTML/CSS developer guys out there, "pinning" can mimic floated elements (float:left or float:right) or positioned elements (position:fixed or position:absolute) combined with top: right: bottom: or left:. Here's how it looks when resized (notice how the other elements are getting squashed up, but our pinned elements are remaining fixed to the top-right corner of the Artboard): What else can Auto Layout do? Pinning is the tip of the iceberg. Auto Layout also helps you: Align objects vertically/horizontally Declare an objects' width (and min/max-width) in % or px Define an offset in % or px Rapidly switch between "Portrait" and "Landscape" for testing Switch to another Artboard Preset for testing in other devices Navigate using a visual diagram or traditional checkbox UI Create "Stacks", the Sketch equivalent of flexbox As mentioned above, these layout options translate to CSS when exported with Launchpad (yes, even the flexbox/Stack settings). Have a play around with it. It's super-straightforward, so you won't have any trouble learning how to align objects or switch between the different device Artboards and orientations. Links Each Artboard is basically a webpage, so linking up screens is easy. Let's set the homepage first. Set Homepage Just underneath the[...]



Async Operations in React Redux Applications

Wed, 20 Sep 2017 17:00:15 +0000

This post was originally posted at Codebrahma. JavaScript is a single-threaded programming language. That is, when you have code something like this … … the second line doesn't get executed till the first one gets completed. Mostly this won't be a problem, since millions of calculations are performed by the client or server in a second. We notice the effects only when we're performing a costly calculation (a task that takes noticeable time to complete --- a network request which takes some time to return back). Why did I show only an API call (network request) here? What about other async operations? An API call is a very simple and useful example for describing how to deal with an asynchronous operation. There are other operations, like setTimeout(), performance-heavy calculations, image loading, and any event-driven operations. While structuring our application, we need to consider how asynchronous execution impacts structuring. For example, consider fetch() as a function that performs an API call (network request) from the browser. (Forget if it is an AJAX request. Just think of the behavior as either asynchronous or synchronous in nature.) The time elapsed while the request is processed on the server doesn't happen on the main thread. So your JS code will keep getting executed, and once the request returns a response it will update the thread. Consider this code: userId = fetch(userEndPoint); // Fetch userId from the userEndpoint userDetails = fetch(userEndpoint, userId) // Fetch for this particular userId. In this case, since fetch() is asynchronous, we won't be having userId when we try to fetch userDetails. So we need to structure it in a way that ensures the second line executes only when the first returns a response. Most modern implementations of network requests are asynchronous. But this doesn't always help, since we depend on the previous API response data for the subsequent API calls. Let's look at how particularly we can structure this in ReactJS/Redux applications. React is a front-end library used for making user interfaces. Redux is a state container that can manage the whole state of the application. With React in combination with Redux, we can make efficient applications that scale well. There are several ways to structure async operations in such a React application. For each method, let's discuss the pros and cons in relation to these factors: code clarity scalability ease of error handling. For each method, we'll perform these two API calls: 1. Fetching city from userDetails (First API response) Let's assume the endpoint is /details. It will have the city in the response. The response will be an object: userDetails : { … city: 'city', … }; 2. Based on the user city we will fetch all restaurants in the city Let's say the endpoint is /restuarants/:city. The response will be an array: ['restaurant1', 'restaurant2', …] Remember that we can do the second request only when we finish doing the first (since it's dependent on the first request). Let's look at various ways to do this: directly using promise or async await with setState using Redux Thunk using Redux-Saga using Redux Observables. Particularly I have chosen the above methods because they're the most popularly used for a large-scale project. There are still other methods that can be more specific to particular tasks and that don't have all the features required for a complex app (redux-async, redux-promise, redux-async-queue to name a few). Promises A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). — Eric Elliot In our case, we'll use the axios library to fetch data, which returns a promise when we make a network request. That promise may resolve and return the response or throw an error. So, once the React Component mounts, we can straight away fetch like this: componentDidMoun[...]



How to Build a React App that Works with a Rails 5.1 API

Wed, 20 Sep 2017 16:00:52 +0000

React + Ruby on Rails = 🔥 React has taken the frontend development world by storm. It's an excellent JavaScript library for building user interfaces. And it's great in combination with Ruby on Rails. You can use Rails on the back end with React on the front end in various ways. In this hands-on tutorial, we're going to build a React app that works with a Rails 5.1 API. You can watch a video version of this tutorial here. To follow this tutorial, you need to be comfortable with Rails and know the basics of React. [affiliate-section title="Recommended Courses"][affiliate-card title="The Best Way to Learn React for Beginners" affiliatename="Wes Bos" text="A step-by-step training course to get you building real world React + Firebase apps and website components in a couple of afternoons. Use coupon code 'SITEPOINT' at checkout to get 25% off." url="https://ReactForBeginners.com/friend/SITEPOINT" imageurl="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/07/1501203893wesbos.jpg"][/affiliate-section] If you don't use Rails, you can also build the API in the language or framework of your choice, and just use this tutorial for the React part. The tutorial covers stateless functional components, class-based components, using Create React App, use of axios for making API calls, immutability-helper and more. What We're Going to Build We're going to build an idea board as a single page app (SPA), which displays ideas in the form of square tiles. You can add new ideas, edit them and delete them. Ideas get auto-saved when the user focuses out of the editing form. At the end of this tutorial, we'll have a functional CRUD app, to which we can add some enhancements, such as animations, sorting and search in a future tutorial. You can see the full code for the app on GitHub: Ideaboard Rails API Ideaboard React frontend Setting up the Rails API Let's get started by building the Rails API. We'll use the in-built feature of Rails for building API-only apps. Make sure you have version 5.1 or higher of the Rails gem installed. gem install rails -v 5.1.3 At the time of writing this tutorial, 5.1.3 is the latest stable release, so that's what we'll use. Then generate a new Rails API app with the --api flag. rails new --api ideaboard-api cd ideaboard-api Next, let's create the data model. We only need one data model for ideas with two fields --- a title and a body, both of type string. Let's generate and run the migration: rails generate model Idea title:string body:string rails db:migrate Now that we've created an ideas table in our database, let's seed it with some records so that we have some ideas to display. In the db/seeds.rb file, add the following code: ideas = Idea.create( [ { title: "A new cake recipe", body: "Made of chocolate" }, { title: "A twitter client idea", body: "Only for replying to mentions and DMs" }, { title: "A novel set in Italy", body: "A mafia crime drama starring Berlusconi" }, { title: "Card game design", body: "Like Uno but involves drinking" } ]) Feel free to add your own ideas. Then run: rails db:seed Next, let's create an IdeasController with an index action in app/controllers/api/v1/ideas_controller.rb: module Api::V1 class IdeasController < ApplicationController def index @ideas = Idea.all render json: @ideas end end end Note that the controller is under app/controllers/api/v1 because we're versioning our API. This is a good practice to avoid breaking changes and provide some backwards compatibility with our API. Then add ideas as a resource in config/routes.rb: Rails.application.routes.draw do namespace :api do namespace :v1 do resources :ideas end end end Alright, now let's test our first API endpoint! First, let's start the Rails API server on port 3001: rails s -p 3001 Then, le[...]



Embedded Signing with the HelloSign API

Wed, 20 Sep 2017 15:30:17 +0000

In less than 4 minutes, we'll walk you through a live embedded signature demonstration. Watch as we embed a signature request from our own example site using HTML and PHP. Prefer to use another language? No problems, HelloSign also has integration code available for Node, Ruby, Python, Java, C# and cURL. With additional branding and customization options available, it's clear to see why signing with HelloSign is easy.

Continue reading %Embedded Signing with the HelloSign API%


Media Files:
https://d3rj1gznkm47xj.cloudfront.net/cdc3661524702b60cf4c5edef20adada.mp4




25 Tested Web Tools & Services for 2017

Wed, 20 Sep 2017 04:52:07 +0000

There are only four months left to go in 2017, and we’re developing a pretty clear picture of this year’s best web tools and services that provide excellent value. Most of them are highly reputed solutions that are getting better and better (like pCloud, xFive or Themify) and some are quite new to the market, but already doing a great job (Goodie, Codester, and others). In this showcase, we’ll quickly review 25 web tools and services that can make life easier for web designers, developers, and other web pros. 1. pCloud pCloud was launched 4 years ago but has already established itself as an excellent, safe storage platform with a full range of features. It is used by all kind of people and companies, including huge corporations like Coca-Cola, Pepsi, IKEA, LinkedIn, Uber, and many others. pCloud’s numbers look as great as the tool: 7 million users, 7 petabytes of maintained information and 1.3 billion files. pCloud is your personal cloud space where you can store all your files and folders in a safe and professional way. It is accessible from any platform or device: web, iOS, Android, macOS, Linux or Windows. The friendly user interface shows you where everything is located and what each feature does. If you install pCloud on your computer (through its desktop application pCloud Drive), you will have a virtual drive that will extend your local storage space. Everything you put on the virtual drive will go into the cloud. Your files will always be secured against attacks, errors or HDD failure. Whatever changes you make in pCloud will be seen immediately on your computer, phone or tablet, and everything is continuously synchronized. Unique in this market, pCloud is offering a Lifetime license that starts from $125 – a one-time cost with great features included (500GB storage, 500GB download link traffic, unlimited remote upload traffic and 30 days of trash history). It also has free plans, up to 20 GB of free storage, and a web extension that will save your favorite web images, videos, and text. Pricing: Lifetime license from $125. 2. Tickera With over 80,000 downloads, Tickera is the best way to sell event tickets with WordPress. Using this plugin, you can quickly deliver digital tickets to your buyers. When using Tickera’s WordPress plugin to sell tickets for your event, you are essentially setting up your own hosted ticketing solution where you control the profits without any middleman fees. Tickera works great with any well-coded WordPress theme out there. There are currently 26 professional add-ons that will further increase Tickera’s functionality. One of the add-ons, for example, will allow you to sell tickets with WooCommerce, another will let your attendees choose the best seats for your show, and another allows you to deliver physical tickets automatically.   The pricing starts from $49/year plus a $70 one-time fee, and comes with a year of premium support and updates. With each license you can use the Tickera plugin on unlimited websites. Pricing: Starting from $49/year + a one-time fee of $70. 3. Xfive With more than 10 years of experience on the market, formerly working under the XHTML brand, Xfive is a complete web development agency serving global customers. These friendly developers can do everything you need in front-end and back-end development, working with JavaScript, WordPress, eCommerce, Sketch to HTML and much more. Xfive has an excellent global track record, working with small companies or large corporations like eBay, Microsoft, Twitter, FOX, and others. We strongly believe that Xfive is one of the top global web development teams that should be approached for a quote and discussion for every project of yours. Pricing: Depends on the project. 4. WhatFontIs WhatFontIs is a popular service that identifies the name of the awesome font that you just saw on a website or in a picture. It is[...]



Building a React Universal Blog App: A Step-by-Step Guide

Tue, 19 Sep 2017 17:00:09 +0000

When the topic of single page applications (SPAs) comes up, we tend to think of browsers, JavaScript, speed, and invisibility to search engines. This is because an SPA renders a page's content using JavaScript, and since web crawlers don't use a browser to view web pages, they can't view and index the content --- or at least most of them can't. This is a problem that some developers have tried to solve in various ways: Adding an escaped fragment version of a website, which requires all pages to be available in static form and adds a lot of extra work (now deprecated). Using a paid service to un-browserify an SPA into static markup for search engine spiders to crawl. Trusting that search engines are now advanced enough to read our JavaScript-only content. (I wouldn't just yet.) Using Node on the server and React on the client, we can build our JavaScript app to be universal (or isomorphic). This could offer several benefits from server-side and browser-side rendering, allowing both search engines and humans using browsers to view our SPA content. In this step-by-step tutorial, I'll show you how to build a React Universal Blog App that will first render markup on the server side to make our content available to search engines. Then, it will let the browser take over in a single page application that is both fast and responsive. Getting Started Our universal blog app will make use of the following technologies and tools: Node for package management and server-side rendering React for UI views Express for an easy back-end JS server framework React Router for routing React Hot Loader for hot loading in development Flux for data flow Cosmic JS for content management To start, run the following commands: mkdir react-universal-blog cd react-universal-blog Now create a package.json file and add the following content: { "name": "react-universal-blog", "version": "1.0.0", "engines": { "node": "4.1.2", "npm": "3.5.2" }, "description": "", "main": "app-server", "dependencies": { "babel-cli": "^6.26.0", "babel-loader": "^7.1.2", "babel-preset-es2015": "^6.24.1", "babel-preset-es2017": "^6.24.1", "babel-preset-react": "^6.24.1", "babel-register": "^6.26.0", "cosmicjs": "^2.4.0", "flux": "^3.1.3", "history": "1.13.0", "hogan-express": "^0.5.2", "html-webpack-plugin": "^2.30.1", "path": "^0.12.7", "react": "^15.6.1", "react-dom": "^15.6.1", "react-router": "1.0.1", "webpack": "^3.5.6", "webpack-dev-server": "^2.7.1" }, "scripts": { "webpack-dev-server": "NODE_ENV=development PORT=8080 webpack-dev-server --content-base public/ --hot --inline --devtool inline-source-map --history-api-fallback", "development": "cp views/index.html public/index.html && NODE_ENV=development webpack && npm run webpack-dev-server" }, "author": "", "license": "ISC", "devDependencies": { "react-hot-loader": "^1.3.0" } } In this file, you'll notice that we've added the following: Babel to package our CommonJS modules and convert our ES6 and React JSX into browser-compatible JavaScript The Cosmic JS official Node client to easily serve our blog content from the Cosmic JS cloud-hosted content API Flux for app data management (which is a very important element in our React application). React for UI management on server and browser React Router for routes on server and browser webpack for bringing everything together into a bundle file. We've also added a script in our package.json file. When we run npm run development, the script copies the index.html file from our views folder into our public folder. Then, it sets the content base for our webpack-dev-server to public/ and enables hot reloading (on file save). Finally, it helps us debug our components at the source and giv[...]



Build a CRUD App Using React, Redux and FeathersJS

Tue, 19 Sep 2017 16:00:47 +0000

Building a modern project requires splitting the logic into front-end and back-end code. The reason behind this move is to promote code re-usability. For example, we may need to build a native mobile application that accesses the back-end API. Or we may be developing a module that will be part of a large modular platform. The popular way of building a server-side API is to use a library like Express or Restify. These libraries make creating RESTful routes easy. The problem with these libraries is that we will find ourselves writing a TON of REPEATING CODE. We will also need to write code for authorization and other middleware logic. To escape this dilemma, we can use a framework like Loopback or Feathersjs to help us generate an API. At the time of writing, Loopback has more GitHub stars and downloads than Feathers. Loopback is a great library for generating RESTful CRUD endpoints in a short period of time. However, it does have a slight learning curve and the documentation is not easy to get along with. It has stringent framework requirements. For example, all models must inherit one of its built-in model class. If you need real-time capabilities in Loopback, be prepared to do some additional coding to make it work. FeathersJS, on the other hand, is much easier to get started with and has realtime support built-in. Quite recently the Auk version was released (because Feathers is so modular, they use bird names for version names) which introduced a vast number of changes and improvements in a number of areas. According to a post they published on their blog, they are now the 4th most popular real-time web framework. It has excellent documentation and they have covered pretty much any area we can think of on building a real-time API. What makes Feathers amazing is its simplicity. The entire framework is modular and we only need to install the features we need. Feathers itself is a thin wrapper built on top of express where they've added new features namely services and hooks. Feathers also allows us to effortlessly send and receive data over web sockets. Prerequisites Before you get started with the tutorial, you'll need to have a solid foundation in the following topics: How to write ES6 JavaScript code How to create React components Immutability in JavaScript How to manage state with Redux On your machine, you will need to have installed recent versions of: NodeJS 6+ Mongodb 3.4+ Yarn package manager (optional) Chrome browser If you have never written a database API in JavaScript before, I would recommend first taking a look at this tutorial on creating RESTful APIs. Scaffold the App We are going to build a CRUD contact manager application using React, Redux, Feathers and MongoDB. You can take a look at the completed project here. In this tutorial, I'll show you how to build the application from the bottom up. We'll kick-start our project using the create-react-app tool. # scaffold a new react project create-react-app react-contact-manager cd react-contact-manager # delete unnecessary files rm src/logo.svg src/App.css Use your favorite code editor and remove all the content in index.css. Open App and rewrite the code like this: import React, { Component } from 'react'; class App extends Component { render() { return (

Contact Manager

); } } export default App; Make sure to run yarn start to ensure the project is running as expected. Check the console tab to ensure that our project is running cleanly with no warnings or errors. If everything is running smoothly, use Ctrl+C to stop the server. Build the API Server with Feathers Let's proceed with generating the back-end API for our CRUD project using the feathers-cli tool. # Install Feathers command-line tool npm inst[...]