Ce diaporama a bien été signalé.
Le téléchargement de votre SlideShare est en cours. ×

Serverless Single Page Apps with React and Redux at ItCamp 2017

Plus De Contenu Connexe

Serverless Single Page Apps with React and Redux at ItCamp 2017

  1. 1. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Serverless Single Page Apps with React and Redux Solution Architect at Haufe Group / #melaniadanciu /mela.ro Melania Andrisan
  2. 2. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Many thanks to our sponsors & partners! GOLD SILVER PARTNERS PLATINUM POWERED BY
  3. 3. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Serverless Mindset Serverless backend The serverless web app Demo
  4. 4. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals SERVERLESS It is all about functions and now servers to manage for these functions
  5. 5. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals SERVERLESS IS: “CORE OF THE FUTURE OF THE DISTRIBUTED COMPONENTS” Satya Nadella Build 2017 Keynote 1
  6. 6. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Evolution…
  7. 7. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Good to know about Serverless • Keeping micro-services stateless and immutable • Focus more on product then infrastructure • Less Control • Less Responsibility • Increased Automation • Continuous scaling • No pay for idle
  8. 8. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Easy to change Static websites Scalable out of the box 0 Cost for idle time Security as a service Authentication and Authorization as a service DB as a service Monitoring as service Identity management NoSQL Easy to maintainCDN as Service Messaging A lot more…
  9. 9. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals AWS
  10. 10. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals My app as 3-tier Architecture App API Gateway Functions Cloud Logic Data Storage Static File Storage Browser Static Website Backend Logic Storage
  11. 11. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals My App on Amazon… S3 API Gateway AWS Lambda Functions Browser DynamoDB
  12. 12. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Microsoft Serverless Offer… Browser Azure Cloud Functions Azure CDN API Management Cosmos DB Azure Blob Storage
  13. 13. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals My Project structure
  14. 14. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Serverless Mindset Serverless backend The serverless web app Demo
  15. 15. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals BACKEND… Lambda Functions, AWS Services: Cognito, Dynamo DB, S3
  16. 16. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals
  17. 17. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals serverless/ handlers/ contact/ lib/ contact.js helper.js event.json handler.js lib/ utils.js serverless.yml My Serverless folder structure
  18. 18. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Contracts Documents Assets Contacts Finance Doc Storage Asset Utilities External Service … API Gateway S3 DynamoDB Cloud Formation with Serverless Framework External Service Lambda Functions
  19. 19. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals functions: authorizerFunc: handler: handlers/authorizer/handler.authorizer contacts: handler: handlers/contact/handler.contact events: - http: method: GET path: /{userId}/contacts/getAll integration: lambda cors: true request: ${file(./templates.yml):request} authorizer: authorizerFunc authorizer: name: authorizer arn: arn:aws:cognito-idp:us-east-2:165979317528:userpool/us-east- 2_xxxxxxxxx serverless.yml
  20. 20. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals var contact = require('./lib/contact'), parser = require('../parser'), env = require('dotenv').config(); module.exports.contact = (event, context, cb) => { var event = parser.parseEvent(event), path = event.path; switch (path) { case '/{userId}/contacts': contact.create(event, context); break; case '/contacts/contact/{id}': contact.view(event, context); break; case '/contacts/update': contact.update(event, context); break; case '/{userId}/contacts/getAll': contact.getAll(event, context); break; case '/{userId}/contacts/delete/{id}': contact.delete(event, context); break; default: context.fail('Invalid api call'); } }; serverless/ handlers/ contact/ lib/ contact.js helper.js event.json handler.js lib/ utils.js serverless.yml
  21. 21. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals var helper = require('./helper'); module.exports.create = (event, context) => { helper.createContact(event).then(result => { context.succeed({ result }); }).catch(err => { context.fail("Error: " + err + " Event: " +JSON.stringify(event) ); }) }; …/handlers/contact/lib/contact.js serverless/ handlers/ contact/ lib/ contact.js helper.js event.json handler.js lib/ utils.js serverless.yml
  22. 22. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals function createContact(data) { let cleanData = utils.removeEmpty(data); return utils.createItem(cleanData, DB_NAME); } …/handlers/contact/lib/helper.js serverless/ handlers/ contact/ lib/ contact.js helper.js event.json handler.js lib/ utils.js serverless.yml
  23. 23. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals function createItem(data, table, item) { return db('put', { TableName: DB_PREFIX + table, Item: data.data }); } …/handlers/lib/utils.js serverless/ handlers/ contact/ lib/ contact.js helper.js event.json handler.js lib/ utils.js serverless.yml
  24. 24. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals DEVELOPMENT & DEBUGGING Serverless-offline, Dynamo DB local
  25. 25. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals More about serverless… https://www.slideshare.net/melaniadanciu/ new-serverless-world-cloud-native-apps http://dev.haufe.com/Serverless_ with_AWS_at_DevTalks/
  26. 26. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Serverless Mindset Serverless backend The serverless web app Demo
  27. 27. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals FRONTEND… React & Redux
  28. 28. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Static Website built with … • React & Redux • Unit Testing with Jest, Enzyme, Expect and sinon • The AJAX calls are done using fetch() • The style is done using a Bootstrap theme • Airbnd Coding style for react apps
  29. 29. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals REACT Facebook A declarative, efficient, and flexible JavaScript library for building user interfaces.
  30. 30. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals
  31. 31. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals import React from 'react'; import { Button, Glyphicon } from 'react-bootstrap'; export default function LoaderButton({ isLoading, text, loadingText, disabled = false, ...props }) { return ( <Button disabled={ disabled || isLoading } {...props}> { isLoading && <Glyphicon glyph="refresh" className="spinning" /> } { ! isLoading ? text : loadingText } </Button> ); } imports Component declaration UI Render
  32. 32. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals JSX Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children). So, anything you can do with JSX you can also be done with just plain JavaScript. https://facebook.github.io/react/docs/react-without-jsx.html
  33. 33. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals JSX Component(ES6) import React from 'react'; import CustomButton from './CustomButton'; function WarningButton() { // return React.createElement(CustomButton, {color: 'red'}, null); return <CustomButton color="red" />; }
  34. 34. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals COMPONENT LIFECYCLE constructor() componentWillMount() render() componentDidMount()
  35. 35. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Component Initialized Props Changed setState() Component Deleted getDefaultProps() componentWillReceiveProps() componentDidUpdate() shouldComponentUpdate()getInitialState() componentWillUpdate() render() componentWillMount() componentDidMount() componentWillUpdate() First time After first time setState() doesn’t Trigger re-rendertrue https://kunigami.blog/2015/04/28/react-js-introduction/
  36. 36. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals CREATE-REACT-APP https://github.com/facebookincubator/create-react-app Create-react-app –> to create the project React-scripts –> npm start; npm test; npm run build No server rendering
  37. 37. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals JavaScript entry point Page Template The main React Component create-react-app my-app
  38. 38. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Modern react app • React, JSX, ES6, and Flow syntax support. • Language extras beyond ES6 like the object spread operator. • A dev server that lints for common errors. • Import CSS and image files directly from JavaScript. • Auto-prefixed CSS, so you don’t need -webkit or other prefixes. • A build script to bundle JS, CSS, and images for production, with sourcemaps. • An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria. https://github.com/facebookincubator/create-react-app#why-use-this
  39. 39. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals React lessons learned • Focus on small reusable components • Do not use component inheritance • Use Type-checking with propTypes • Check that your UI is working using unit test and see their result in real time • Take care of performance using immutable elements or implement shouldComponentUpdate • Read the React documentation carefully and understand the concepts behind it, there is no 2-way binding with React
  40. 40. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals REDUX Dan Abramov App data-flow architecture App state management
  41. 41. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals LEARN ABOUT IT Dan Abramov - Live React: Hot Reloading with Time Travel at react-europe 2015 - https://www.youtube.com/watch?v=xsSnOQynTHs
  42. 42. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Flux Data-Flow Architecture Action Dispatcher Store View
  43. 43. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Flux Data-Flow Action Action Dispatcher Store View
  44. 44. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Flux Data-Flow Action Action Dispatcher Store View [controller-view] Actions creators – helper methods, create an action from method params assign a type and provide it to the dispatcher. Every action is sent to all Stores via callbacks After stores updated themselves, They emit a change event. The view listen to change Events, retrieve data from the store and provide the new data to the entire tree Of their children views.
  45. 45. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals REDUCERS+FLUX = REDUX Elm + Flux => Redux Dan Abramov - The Redux Journey at react-europe 2016 https://www.youtube.com/watch?v=uvAXVMwHJXU
  46. 46. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Redux Data-Flow Reducer [Pure function] UI View Store [Holds current state] Action Creator onClick() events User Interaction Update state New State Dispatch action Actions are events
  47. 47. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Constrains and their benefits • Single State tree • Actions Describe Updates • Reducers Apply Updates
  48. 48. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals ACTIONS = events
  49. 49. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals export function createContactSuccess(contact) { return { type: ActionTypes.CREATE_CONTACT_SUCCESS, contact: contact } } actions/contactActions.js
  50. 50. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals REDUCER Pure functions
  51. 51. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals import ActionTypes from '../actions/constants/actionTypes' import InitialState from './initialState' export default function displayReducer(state =InitialState.display, action) { switch (action.type) { case ActionTypes.DISPLY_CONTACT: return { ...state, selectedContact: action.contact } default: return state; } } Contact reducer
  52. 52. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Combine reducers: reducers/index.js const rootReducer = combineReducers({ contacts, //short hand property name addressCategories, display, assets, userSettings, ajaxStatus, modals: modalReducer }); export default rootReducer;
  53. 53. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals SELECTORS Like Map state to props (state, …args) =>derivation
  54. 54. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Selectors export function contactsFormatedForDropdown(contacts) { return contacts.map(contact => { return { value: contact.id, text: contact.firstName + ' ' + contact.lastName } }) }
  55. 55. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals STORE The application state Dispatch action & Register listener
  56. 56. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals import {createStore, applyMiddleware} from 'redux'; import rootReducer from '../reducers'; import thunk from 'redux-thunk'; export default function configureStore(initialState){ return createStore( rootReducer, initialState, //handle async actions in API calls applyMiddleware(thunk) //for dev mode applyMiddleware(reduxImmutableStateInvariant()) ); } store/configureStore.js
  57. 57. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals REDUX THUNK https://github.com/gaearon/redux-thunk Redux Thunk middleware allows you to write action creators that return a function instead of an action.
  58. 58. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals export function saveContact(contact, userToken) { //thunk - return function (dispatch, getState) { dispatch(beginAjaxCall()); return ContactsApi.saveContact(contact, userToken).then((savedContact) => { contact.id ? dispatch(updateContactSuccess(savedContact)) : dispatch(createContactSuccess(savedContact)); }).catch(error => { dispatch(ajaxCallError()); throw (error); }); } } Save a contact action
  59. 59. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Redux Lesson Leaned • The entire state of you app is a plain js Object an Immutable State Object • Redux is build on top of functional programming concepts • It heavily uses pure functions • When you learn it do not use starter kits • It gives order to your code • Redux DevTools
  60. 60. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Resources • https://kunigami.blog/2015/04/28/react-js-introduction/ • https://github.com/facebookincubator/create-react-app • https://facebook.github.io/react/ • https://app.pluralsight.com/library/courses/react-flux-building- applications/table-of-contents • https://thenewstack.io/best-practices-for-developing-cloud-native- applications-and-microservice-architectures/ • http://flomotlik.me/blog/challenges-of-serverless-in-2017/ • https://github.com/aws/amazon-cognito-identity-js • https://medium.com/komenco/react-autobinding-2261a1092849 • https://github.com/airbnb/javascript/tree/master/react • http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Do cumentClient.html#batchWrite-property
  61. 61. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Serverless Mindset Serverless backend The serverless web app Demo
  62. 62. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals DEMO
  63. 63. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals • Be stateless on the backend and on the frontend • Think functional and make your functions as small as possible • Make you client independent of you backend with no server rendering • Automate as much as you can your entire development, debugging, testing and deployment - it saves a lot of time • And yes, using the cloud provider services means being locked in with that cloud provider, so you need to manage this risk 5 thinks to take way
  64. 64. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals SEE YOU NEXT TIME! Thanks
  65. 65. @ITCAMPRO #ITCAMP17Community Conference for IT Professionals Q & A

Notes de l'éditeur

  • Hi,

    I am Melania Andrisan, I am coming from Timisoara where I am a Solution Architect for Haufe Group. I am very passionate about what the new technologies have to offer every day, and I read a lot. In the last 3 months I worked at a completely new project done entirely Serverless, Built with React, Redux and AWS(Amazon WebServices). You might wander why Serverless, what is this serverless and what you can so with it. Does any of you has experience with Serverless Architecure?... O, super so I see a couple of hands up, this means I will not bore you with useless details that you already know. 
  • This is the how I decided to split this presentations. I will have a part about entering in the serverless minsest, a part about how I built the serverless backend, a part about serverless web app and the last 15 minutes or so will be a demo of my app and the code behind it.
  • First of all, What is serverless? For me serverless means I do not have any servers to manage, I have just my code to write and to focus on. Serverless main component is the function, you build the function, you test the function, deploy it and then you give the responsibility to your Cloud provider to make it available and fully scalable. It is very important to keep this function small, easy to change and maintain and include just the frameworks that you rely need for that particular function.
  • This is what Satya Nadella said a couple of weeks ago in the Keynote at Build: that Serverless basically is: “Core of the future of the distributed components”
    In a nutshell if you need to have your application distributed, scalable and easy to maintain you should have a look at this type of architecture.

    As of Build day Microsoft offers end to end support for serverless development in Azure, you develop, debug and test your functions with Visual Studio and deploy them into Azure from there. And this is huge because you access all sort of services from the cloud like for example data bases an you can still debug on your machine.
  • This concept is not new this concept of having the unit of work a function appeared in the 80’s and it just got into our attention again when Amazon launched Amazon Lambda Functions 3 years ago. The architecture of building an web app evolved from Monolith to (SOA) Service oriented Architecture to Microservices and now is Serverless. There are tones of documentation of how you can move you app from monolith to microservices which means we had a lot of monoliths and I am sure a lot of you interacted with it at least one in your carrier, I do not need to explain you what it is. You had full control over it but not so much flexibility when changing it after a couple of years and usually you will scale vertically not horizontally, with microservices and containers you have much more flexibility and scalability but you need to still manage them and pay when you do not use them, with serverless and this small functions you are fully scalable, easy to change and no need to manage and on top of this you do not pay for idle time. You have all of this with Serverless and a lot more…
    My presentation is not how you can move from one architecture to the other is to start all fresh completely server less.

  • All the functions you create can be exposed via HTTP and make them publically available, the best approach is to put in front of them an API Gateway to make their management easy. Having them in this way, I will call them APIs or services.
    To be able to make everything working you need to make all the services stateless. What this means is that you need to save your state elsewhere, every time when you will make a request to you service you will not know what was the previous request and its results, for sure you can have that information but it is in a sort of data storage, being it SQL, NoSQL, file storage or blob storage.
    This micro-services need to be also immutable and you can understand a lot from what immutability is, what I mean hear in this context is that once you have you function deployed you can come with a new implementation in a later time and change it but you will have the same expected functionality there, the same version, usually they are no versions in serverless, in case you need new functionality you just create a new function and that’s it.
    When you give all the responsibility of managing the servers to your cloud provider you remain with less responsibility and also less control, and you need to wrap your head around this. You need to be comfortable with this and to accept it not to fight it. Because with it comes increased automation, continuous scaling at a very small costs because if you go fully serverless you will not pay for idle time.
  • This are just some interesting points serverless offers. There are thigs like security, monitoring, authentication and authorization as a services… and …
  • Here are all the services from Amazon. You need a couple of hour to read about them and a couple of re:Invent videos to understand how to put them together but then you can start building your application and have available services in a couple of days with proper authentication and authorization and all the needed security levels.
  • And now let’s have a look at the classical 3 tiers architecture and what does it means to have it in a Cloud Native App. In a 3-tier architecture usually we have an website, a logic component and a data storage. Of course the website needs to be stored some ware and to access the logic in a common way we can have an API Gateway put in place.
    To have a website we can have some HTML and JS and publish it, the heavy logic is done in the Cloud Logic and we will see what are the offers on the market.
  • This is how my app looks like. Amazon has a very strong implementation for Serverless offering all the needed pieces to go all Serverless. To exposes your Static Website you need to deploy it in S3(their file storage) and check a check box which says you want to make this content available over HTTP and to accelerate the delivery of your website you can enable a CDN and the Amazon offer for this is Amazon CloudFront.
    Now that we have our frontend we need to take care of our backend too, to expose properly our Logic written as Lambda Functions we set un an API Gateway which has exactly this name in AWS and for storage there are a lot of offers but to have the DB as service an No-SQL, because this is the trend in serverless, but is not mandatory, we can use DynamoDB, a very strong No-SQL implementation in Amazon which is offered as a service.

    In case you want to document your API properly the API Gateway documentation generation is done using Swager.

    A similar architecture can be done using Azure:
  • You have Azure blob storage with Azure CDN for frontend and Azure cloud functions and API Management on the backend. For storage they offer and very cool DB launched at Build the Cosmos DB. For those of you who do not know, it is a DB fully scalable which offer APIs for SQL, NoSQL and file storage all in one. Just check it out.

    https://azure.microsoft.com/en-us/services/documentdb/
    http://gauravmantri.com/2012/05/09/comparing-windows-azure-blob-storage-and-amazon-simple-storage-service-s3part-i/
  • Moving one to the implementations, This is how my project structure looks like.
    I bring all my dependences using NPM, And I recommend using NVM for versioning management of node because in this way you can have different versions of node running on your machine and use the needed one for every project.
    I have a couple of scripts for deployment written using Gulp
    I use linters to have syntactic errors highlighted.
    And I have my project split between web(react) and Serverless folder created using Serverless Framework.
  • First the backend
  • To put all my services together I used Serverless framework which can create us a structure of the Serverless project. Even though it says just AWS Lambda on their main page they offer support for all the other major Cloud providers like Azure, Google and IBM.
  • This is how the main folder structure of my serverless looks like. I show you this because it toke me a couple of hours to find a proper arrangement. The most important 2 files are handler.js which defines the lambda function and serverless.yml which defines the API gateway, with all the needed endpoints exposed by the handler and the needed authentication for it. We also can define s3 buckets and dynamoDB tables.
  • And here is the definition of the endpoint of getting all the needed information for all contacts.
  • Here is how a Lambda handler looks like. I have all the APIs for a contact here defined. Let’s take for example the create contact.
  • This is how I make the request and I wait to get the response back using a promise.
  • Then I have the helpers to make any needed changes to the data and pass the needed data to the utils function.
  • I used utils to make small reusable functions. More about this in the demo part of the presentation.
  • To be able to develop and debug this locally you can install serverless offline and dynamo DB locally and doing this you will not be forces to deploy everything to the cloud to test you changes.
  • There are a lot of other things which can be said about the server and a lot of service integration challenges but for now I am happy of I made you curious to dig more into it. Here you can find my slides and a blog post published by me last week, have a look.
  • Now moving on into the how I built my static website.
  • The fronted is buit using React and Redux and a lot of other JS frameworks.
  • In my opinion building the frontend using React and Redux is a good choice if you want to use the same paradigm as you used when you built your services and I will come to this in a sec. I wanted to have my Web App testable and also tested and I used Jest, Enzyme, Expect and sinon to do that. To get the data from Lambda I am using fetch() ore you can use axios, it is a methor of preferences. To have all the application looking good we added a Bootstrap team and everything looked perfect, or at least as we wanted it to look.
  • In my opinion React works for client like Lambda works for server. As you can see it is flexible, efficient and also declarative, you have components, elements and the possibility to manipulate the virtual DOM. How many of you gave React a try? Cool, I hope you enjoyed it as much as I do. In the next minutes I will just show you some tips and tricks and cool things I like about react and how I applied them in my project. I will present them in the way I learned them and this is how it was…

    http://busypeoples.github.io/post/react-component-lifecycle/
    https://www.slideshare.net/binary-studio/academy-pro-react-js
    https://facebook.github.io/react/blog/2015/12/18/react-components-elements-and-instances.html
  • First… This are some interesting courses on Pluralsight and if you have subscription I will really recommend them. I started my app with React and then Added Flux, but for me Flux was to verbose and to be able to achieve the same functionality that I have today with Redux I had to write to much code in my opinion and my code it was not so clear like it is today with Redux. Flux and Redux have the same idea underneath and I will show it to you in a bit.
  • But first React… React is an UI framework built by Facebook. It is not an MVC framework it is just a framework fro the View. It is Open Source and you can find it on github, this means that if you are curious to see how something is implemented you can have a look. For sure it sounds strange to write JS and HTML together because all these years we militated for separation on concerns but the main idea is really to separate functional component and just to include the needed Elements at the render time in the displayed component. To make the React development easier include in your browser the react dev tools.
    The most important 2 parts of React are the components and the algorithm behind rendering them. The components are small UI parts and they look like this: You have a js file where you can include different libraries and also CSS, you have the component declaration with the needed properties, Ya… I know those 3 dots look strange but that is just a spread operator, which iterates through all the other properties and puts them under props, and in the end you have the most important part, the render where you add your JSX declaration or you just can include plain old JS.
    The algorithm used by React is O(n) for updating the Virtual DOM tree structure and is using heuristics to be just O(n).
  • We know how a component looks and now we need to learn how to write the elements in a way React knows to render them and for that we have JSX, but not only JSX.
    In case you do not want to use compilation in you build environment you can use just JS objects. It is a matter of choice and also if you get used to it or not. For us was easy to adapt to this way of writing js and UI and we like it. In case you want to not use JSX you can have a look at the reference link and use the plain JS.

  • Something like this.
    Either you use the createElement function or you use the JSX tags directly.
  • Them components might be classes or functions, and you can handle different states of them.
    Now, moving on to understand all of this… an interesting part is the component lifecycle and what you can do in different stages. For example when you initialize a component it will call the constructor, them the componentWillMount then render and in the end the componetnDidMount. Is important to know this because you can do all sorts of animations within you app.
  • This is an interesting diagram, take it as reference when you want to handle all the state of you component. To see what happens before render and what will happen after that. For a more in depth walkthrough I recommend reading the article from the link.
    In a couple of words to be sure the rendering algorithm works well you should make UI updates when you need them, and to be aware that just a setState() will not change the UI, but the shouldComponentUpdate() function will decide when this will happen and you can implement this function when you fill appropriate, usually in complex components to not trigger a re-render of an entire part of you UI.

    Render is a declarative function and because if it the algorithm of updating the UI is so powerful.
  • After I understood how React works and how I should build the components. Now I want to create my static website.
    Having the application instantly showing your development changes is incredibly powerful and create-react-app offers you this possibility with the call of a single script, npm start and also the possibility to see your tests by typing npm test. All of this is posible because of Webpack and the hotr reload implemented in it. On top of it create-react-app and the name of you app you can create a boilerplate project with all the needed elements of React. Another powerful command is npm build witch creates a build folder with just the needed files which you can deploy statically and you will not need any servers to render you application. And you can deploy it in a simple storage and expose it via HTTP. There is no server rendering with it, in the end you will have just a static website.
  • Here is how a Simple React App looks like. The most important pages are called index, the HTML one is the the Page template the other one is the main JS entry point. The App.js file is a react component displayed in index.js and the other 2 App files are 2 things nice to have, if you have come css related to that page you can add it in app.js and if you would like to write some test you can write them in app.test.js. The main test runner used with react is Jest, but you can use others too, like mocca.
    Why I recommend using this is because you have just one dependency(which includes Webpack, Babel, ESLint), it has no configuration and actually No Lock-In: You can “eject” to a custom setup at any time. Run a single command, and all the configuration and build dependencies will be moved directly into your project, so you can pick up right where you left off.
  • And with it you will have all of this and you will not have to bother about linter, suport for ES6 and a lot more.

  • React builds and maintains an internal representation of the rendered UI. It includes the React elements you return from your components. This representation lets React avoid creating DOM nodes and accessing existing ones beyond necessity, as that can be slower than operations on JavaScript objects. Sometimes it is referred to as a "virtual DOM", but it works the same way on React Native.

    When a component's props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM.
  • There are another dozen of data-flow frameworks but in the community opinion Redux is the winner for complex apps as static websites. There is MobX, Relay, Falcor and a lot more. Google it if you are curious. There are some which are built on top of Flux, the first framework built by Facebook but there are others which are built completely new.
    In my case I choose Redux because it was easy to understand and to write code and somehow it was the natural move to make after I started with Flux.
  • On how to user Redux and a to see how Dan Abramov the creator or Redux buid the framework you should see this video.
  • This are the main components of the Flux architecture: Action, Dispatcher, Store and View, more as a Controller View which gets the changes from the store and pass them to its children.
  • The view can trigger actions an so this actions will be handled by the dispatcher and passed to the store.
  • The Action creators are just helper methods and I will speak about them in the redux implementation.

    It has A single dispatcher, multiple stores.
  • Reducers are pure functions which returrn a new state based on the parameters it get. The reducers + Flux architecture is Redux. What is a pure function Pure functions return a new value based on arguments passed to them. They don’t modify existing objects; instead, they return a new one.
  • https://www.smashingmagazine.com/2016/06/an-introduction-to-redux/

    As I see it Redux is a simple and clearer way of implementing the Flux architecture. There is no separate dispatcher function, there is just one store which is the one source sf true for your state and is able to dispatch all the changes to the Action Creators.
  • He did not focused only on the functionality of Flux, he focused also on some constrains imposed by be architecture.
    There is just one plain js object which holds the state
    There is no way of setting the state, you need to emit an action to do that
    And to make the update visible you need to implement a special function named reducer which will return you the new state

    And because you have this separation the development, debugging and testing is incredibly easy.
  • Actions are basically events which return a type and a payload and look like this
  • I have a list of Action types and the one here is create_contact_success and the payload is the contact which was created.
  • As I said In Redux, reducers are functions (pure) that take the current state of the application and an action and then return a new state. What is a pure function Pure functions return a new value based on arguments passed to them. They don’t modify existing objects; instead, they return a new one. For this reason, they are very predictable.
  • And here is how a reducer looks like. Base on the action type it receives and the current state it returns a new state.
  • You can even combine reducers and make a root reducers exactly like you have a root component for React.
  • You have also selectors which are like map state to props from react. You have your state, some arguments and you return a derived date useful data for the UI.
  • Here is how a selector looks, I created one to display my contacts list in a dropdown.
  • Store is the object that holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. 
  • And here is how my configure store looks like.
    Basically you return the store with the root reducer the initial state and some other configurations like thunk, I use thunk to handle the async actions for my API calls.
  • Basically react thunk is a middleware which allows you to write actions creators that return a function instead of an action.
  • And here is how it looks.
  • It is able to treat functions as first-class objects.
    It is able to pass functions as arguments.
    It is able to control flow using functions, recursions and arrays.
    It is able to use pure, recursive, higher-order, closure and anonymous functions.
    It is able to use helper functions, such as map, filter and reduce.
    It is able to chain functions together.
    The state doesn’t change (i.e. it’s immutable).
    The order of code execution is not important.

    The functions can be copied and pasted anywhere without any modification. Functions that are isolated in scope and that perform only one task will depend less on other modules in an app, and this reduced coupling is another benefit of functional programming.
  • And now the Demo.
  • And now let me show you my app:
    I will open the terminal and type gulp serve and as you can see this will start the client, start the dynamo db locally and start also the offline server to call my APIs locally. 
    It goes to all of this exposing the API Gateway routes, creating all the needed tables, exposing the app on http://localhost:3000 and after this this terminal window will capture all the requests done to my services. 
    How I was able to have all of this with a single command? This is how…
    I have here the gulp file in the route of my project and here I created a set of gulp tasks like start-dynamodb and this will start the dynamodb locally, the start client will run nom start in the web folder and you can specify if you want to run the app on HTTP or HTTPS locally. And a lot more. 
    What I like about gulp is that you can specify very easy all the needed commands, split then in tasks and then combined the tasks as you need it. For example to start my app locally I need to run this tasks, to start just the server are just this and to deploy it are these once. 

    I did not reinvent this I used a boilerplate project from git called serverless-react-boilerplate  [https://github.com/99xt/serverless-react-boilerplate] 

×