Set Up Routing in PHP Applications Using the Symfony Routing Component

Today, we’ll go through the Symfony Routing component, which allows you to set up routing in your PHP applications.

What Is the Symfony Routing Component?

The Symfony Routing Component is a very popular routing component which is adapted by several frameworks and provides a lot of flexibility should you wish to set up routes in your PHP application.

If you’ve built a custom PHP application and are looking for a feature-rich routing library, the Symfony Routing Component is more than a worth a look. It also allows you to define routes for your application in the YAML format.

Starting with installation and configuration, we’ll go through real-world examples to demonstrate a variety of options the component has for route configuration. In this article, you’ll learn:

  • installation and configuration
  • how to set up basic routes
  • how to load routes from the YAML file
  • how to use the all-in-one router

Installation and Configuration

In this section, we’re going to install the libraries that are required in order to set up routing in your PHP applications. I assume that you’ve installed Composer in your system as we’ll need it to install the necessary libraries that are available on Packagist.

Once you’ve installed Composer, go ahead and install the core Routing component using the following command.

Although the Routing component itself is sufficient to provide comprehensive routing features in your application, we’ll go ahead and install a few other components as well to make our life easier and enrich the existing core routing functionality.

To start with, we’ll go ahead and install the HttpFoundation component, which provides an object-oriented wrapper for PHP global variables and response-related functions. It makes sure that you don’t need to access global variables like $_GET, $_POST and the like directly.

Next, if you want to define your application routes in the YAML file instead of the PHP code, it’s the YAML component that comes to the rescue as it helps you to convert YAML strings to PHP arrays and vice versa.

Finally, we’ll install the Config component, which provides several utility classes to initialize and deal with configuration values defined in the different types of file like YAML, INI, XML, etc. In our case, we’ll use it to load routes from the YAML file.

So that’s the installation part, but how are you supposed to use it? In fact, it’s just a matter of including the autoload.php file created by Composer in your application, as shown in the following snippet.

Set Up Basic Routes

In the previous section, we went through the installation of the necessary routing components. Now, you’re ready to set up routing in your PHP application right away.

Let’s go ahead and create the basic_routes.php file with the following contents.

Setting up routing using the Symfony Routing component usually goes through a series of steps as listed below.

  • Initialize the Route object for each of your application routes.
  • Add all Route objects to the RouteCollection object.
  • Initialize the RequestContext object which holds the current request context information.
  • Initialize the UrlMatcher object by passing the RouteCollection object and the RequestContext object.

Initialize the Route Object for Different Routes

Let’s go ahead and define a pretty basic foo route.

The first argument of the Route constructor is the URI path, and the second argument is the array of custom attributes that you want to return when this particular route is matched. Typically, it would be a combination of the controller and method that you would like to call when this route is requested.

Next, let’s have a look at the parameterized route.

The above route can match URIs like foo/1, foo/123 and similar. Please note that we’ve restricted the {id} parameter to numeric values only, and hence it won’t match URIs like foo/bar since the {id} parameter is provided as a string.

Add All Route Objects to the RouteCollection Object

The next step is to add route objects that we’ve initialized in the previous section to the RouteCollection object.

As you can see, it’s pretty straightforward as you just need to use the add method of the RouteCollection object to add route objects. The first argument of the add method is the name of the route, and the second argument is the route object itself.

Initialize the RequestContext Object

Next, we need to initialize the RequestContext object, which holds the current request context information. We’ll need this object when we initialize the UrlMatcher object as we’ll go through it in a moment.

Initialize the UrlMatcher Object

Finally, we need to initialize the UrlMatcher object along with routes and context information.

Now, we have everything we could match our routes against.

How to Match Routes

It’s the match method of the UrlMatcher object which allows you to match any route against a set of predefined routes.

The match method takes the URI as its first argument and tries to match it against predefined routes. If the route is found, it returns custom attributes associated with that route. On the other hand, it throws the ResourceNotFoundException exception if there’s no route associated with the current URI.

In our case, we’ve provided the current URI by fetching it from the $context object. So, if you’re accessing the http://your-domain/basic_routes.php/foo URL, the $context->getPathInfo() returns foo, and we’ve already defined a route for the foo URI, so it should return us the following.

Now, let’s go ahead and test the parameterized route by accessing the http://your-domain/basic_routes.php/foo/123 URL.

It worked if you can see that the id parameter is bound with the appropriate value 123.

Next, let’s try to access a non-existent route like http://your-domain/basic_routes.php/unknown-route, and you should see the following message.

So that’s how you can find routes using the match method.

Apart from this, you could also use the Routing component to generate links in your application. Provided RouteCollection and RequestContext objects, the UrlGenerator allows you to build links for specific routes.

The first argument of the generate method is the route name, and the second argument is the array that may contain parameters if it’s the parameterized route. The above code should generate the /basic_routes.php/foo/123 URL.

Load Routes From the YAML File

In the previous section, we built our custom routes using the Route and RouteCollection objects. In fact, the Routing component offers different ways you could choose from to instantiate routes. You could choose from various loaders like YamlFileLoader, XmlFileLoader, and PhpFileLoader.

In this section, we’ll go through the YamlFileLoader loader to see how to load routes from the YAML file.

The Routes YAML File

Go ahead and create the routes.yaml file with the following contents.

An Example File

Next, go ahead and make the load_routes_from_yaml.php file with the following contents.

The only thing that’s different in this case is the way we initialize routes!

We’ve used the YamlFileLoader loader to load routes from the routes.yaml file instead of initializing it directly in the PHP itself. Apart from that, everything is the same and should produce the same results as that of the basic_routes.php file.

The All-in-One Router

Lastly in this section, we’ll go through the Router class, which allows you to set up routing quickly with fewer lines of code.

Go ahead and make the all_in_one_router.php file with the following contents.

Everything is pretty much the same, except that we’ve instantiated the Router object along with the necessary dependencies.

With that in place, you can straight away use the match method of the Router object for route mapping.

Also, you will need to use the getRouteCollection method of the Router object to fetch routes.

Conclusion

Go ahead and explore the other options available in the Routing component—I would love to hear your thoughts!

Today, we explored the Symfony Routing component, which makes implementation of routing in PHP applications a breeze. Along the way, we created a handful of examples to demonstrate various aspects of the Routing component. 

I hope that you’ve enjoyed this article, and feel free to post your thoughts using the feed below!


Source: Nettuts Web Development

Creating Pretty Popup Messages Using SweetAlert2

Every now and then, you will have to show an alert box to your users to let them know about an error or notification. The problem with the default alert boxes provided by browsers is that they are not very attractive. When you are creating a website with great color combinations and fancy animation to improve the browsing experience of your users, the unstyled alert boxes will seem out of place.

In this tutorial, you will learn about a library called SweetAlert2 that allows us to create all kinds of alert messages which can be customized to match the look and feel of our own website.

Display Simple Alert Messages

Before you can show all those sweet alert messages to your users, you will have to install the library and include it in your project. If you are using npm or bower, you can install it by running the following commands:

You can also get a CDN link for the latest version of the library and include it in your webpage using script tags:

Besides the JavaScript file, you will also have to load a CSS file which is used to style all the alert boxes created by the library:

Once you have installed the library, creating a sweet alert is actually very easy. All you have to do is call the swal() function. Just make sure that the function is called after the DOM has loaded.

There are two ways to create a sweet alert using the swal() function. You can either pass the title, body text and icon value in three different arguments or you can pass a single argument as an object with different values as its key-value pairs. Passing everything in an object is useful when you want to specify values for multiple arguments.

When a single argument is passed and it is a string, the sweet alert will only show a title and an OK button. Users will be able to click anywhere outside the alert or on the OK button in order to dismiss it.

When two arguments are passed, the first one becomes the title and the second one becomes the text inside the alert. You can also show an icon in the alert box by passing a third argument. This can have any of the five predefined values: warning, error, successinfo, and question. If you don’t pass the third argument, no icon will be shown inside the alert message.

Configuration Options to Customize Alerts

If you simply want to show some basic information inside an alert box, the previous example will do just fine. However, the library can actually do a lot more than just simply show users some text inside an alert message. You can change every aspect of these alert messages to suit your own needs.

We have already covered the title, the text, and the icons inside a sweet alert message. There is also an option to change the buttons inside it and control their behavior. By default, an alert will only have a single confirm button with text that says “OK”. You can change the text inside the confirm button by setting the value of the confirmButtonText property. If you also want to show a cancel button in your alert messages, all you have to do is set the value of showCancelButton to true. The text inside the cancel button can be changed using the cancelButtonText property.

Each of these buttons can be given a different background color using the confirmButtonColor and cancelButtonColor properties. The default color for the confirm button is #3085d6, while the default color for the cancel button is #aaa. If you want to apply any other customization on the confirm or cancel buttons, you can simply use the confirmButtonClass and cancelButtonClass properties to add a new class to them. Once the classes have been added, you will be able to use CSS to change the appearance of those buttons. You can also add a class on the main modal itself by using the customClass property.

If you interacted with the alert messages in the first example, you might have noticed that the modals can be closed by pressing either the Enter or Escape key. Similarly, you can also click anywhere outside the modal in order to dismiss it. This happens because the value of allowEnterKey, allowEscapeKey, and allowOutsideClick is set to true by default.

When you show two different buttons inside a modal, the confirm button is the one which is in focus by default. You can remove the focus from the confirm button by setting the value of focusConfirm to false. Similarly, you can also set the focus on the cancel button by setting the value of focusCancel to true.

The confirm button is always shown on the left side by default. You have the option to reverse the positions of the confirm and cancel buttons by setting the value of reverseButtons to true.

Besides changing the position and color of buttons inside the alert messages, you can also change the background and position of the alert message or the backdrop around it. Not only that, but the library also allows you to show your own custom icons or images in the alert messages. This can be helpful in a lot of situations.

You can customize the backdrop of a sweet alert using the backdrop property. This property accepts either a Boolean or a string as its value. By default, the backdrop of an alert message consists of mostly transparent gray color. You can hide it completely by setting the value of backdrop to false. Similarly, you can also show your own images in the background by setting the backdrop value as a string. In such cases, the whole value of the backdrop string is assigned to the CSS background property. The background of a sweet alert message can be controlled using the background property. All alert messages have a completely white background by default.

All the alert messages pop up at the center of the window by default. However, you can make them pop up from a different location using the position property. This property can have nine different values with self-explanatory names: top, top-start, top-end, center, center-start, center-end, bottom, bottom-start, and bottom-end.

You can disable the animation when a modal pops up by setting the value of the animation property to false. The library also provides a timer property which can be used to auto-close the timer once a specific number of milliseconds have passed.

In the following example, I have used different combinations of all the properties discussed in this section to create four different alert messages. This should demonstrate how you can completely change the appearance and behavior of a modal created by the SweetAlert2 library.

Important SweetAlert2 Methods

Initializing different sweet alert messages to show them to users is one thing, but sometimes you will also need access to methods which control the behavior of those alert messages after initialization. Fortunately, the SweetAlert2 library provides many methods that can be used to show or hide a modal as well as get its title, text, image, etc.

You can check if a modal is visible or hidden using the isVisible() method. You can also programmatically close an open modal by using the close() or closeModal() methods. If you happen to use the same set of properties for multiple alert messages during their initialization, you can simply call the setDefaults({configurationObject}) method in the beginning to set the value of all those properties at once. The library also provides a resetDefaults() method to reset all the properties to their default values.

You can get the title, content, and image of a modal using the getTitle(), getContent(), and getImage() methods. Similarly, you can also get the HTML that makes up the confirm and cancel buttons using the getConfirmButton() and getCancelButton() methods.

There are a lot of other methods which can be used to perform other tasks like programmatically clicking on the confirm or cancel buttons.

Final Thoughts

The SweetAlert2 library makes it very easy for developers to create custom alert messages to show to their users by simply setting the values of a few properties. This tutorial was aimed at covering the basics of this library so that you can create your own custom alert messages quickly. 

To prevent the post from getting too big, I have only covered the most commonly used methods and properties. If you want to read about all the other methods and properties which can be used to create advanced alert messages, you should go through the detailed documentation of the library.

Don’t forget to check out the other JavaScript resources we have available in the Envato Market, as well.

Feel free to let me know if there is anything that you would like me to clarify in this tutorial.


Source: Nettuts Web Development

Create Interactive Gradient Animations Using Granim.js

Gradients can instantly improve the look and feel of a website, if used carefully with the right color combination. CSS has also come a long way when it comes to applying a gradient on any element and animating it. In this tutorial, we will move away from CSS and create gradient animations using a JavaScript library called Granim.js.

This library draws and animates gradients on a given canvas according to the parameters you set when creating a Granim instance. There are different methods which can be used to make your gradient respond to different user events like a button click. In this tutorial, we will learn about this library in detail and create some simple but nice gradient animation effects.

Create Solid Color Gradient Animations

Before we begin creating any gradient, you will have to include the library in your project. For this, you can either download Granim.js from GitHub or link directly to a CDN. The library version that I am using in this tutorial is 1.1. Some methods that we will discuss here were only added in version 1.1, so using an older library version when following this tutorial will not always give the expected result. Keeping these points in mind, let’s create our first gradient using Granim.js.

Every time you create a new Granim instance, you can pass it an object of key-value pairs, where the key is the name of a particular property and the value is the value of the property. The element property is used to specify the CSS selector or DOM node which will point to the canvas on which you want to apply a particular gradient.

When you create a gradient animation where the colors change from a relatively light value to a darker value, it might become impossible to read some text that you have positioned on the canvas. For example, the initial gradient applied on an element might be a combination of yellow and light green. In such cases, the text of the canvas would have to be darker for users to be able to read it properly. 

Similarly, the gradient might consist of dark red and black at some other point, and in such cases the dark text would not be easy to read. Granim.js solves this problem for you by allowing you to specify a container element on which you can add the dark and light classes to style the text or other elements accordingly. The value of the elToSetClassOn property is set to body by default, but you can also specify any other container element. The dark and light class names are updated automatically based on the average color of the gradient.

The elToSetClassOn property does not work by itself. You will also have to specify a name for the Granim instance that you created using the name property. If you set the name to something like first-gradient, the name of the classes applied on the container element will become first-gradient-light or first-gradient-dark based on how light or dark the gradient currently is. This way, any element which needs to change its color based on the lightness or darkness of the gradient will be able to do so with ease.

The direction in which a gradient should be drawn can be specified using the direction property. It has four valid values: diagonal, left-right, top-bottom, and radial. The gradients that you create will not move in those particular directions—they will just be drawn that way. The position of the gradient doesn’t change during the animation; only its colors do.

There is also a states property, which accepts an object as its value. Each state specified inside the states object will have a name and a set of key-value pairs. You can use the gradients property to specify different colors which should make up a particular gradient. You can set the value of this property to be equal to an array of gradients. 

Granim.js will automatically create an animation where the colors of the gradient change from one set to another. The transition between different gradients takes 5,000 milliseconds by default. However, you can speed up or slow down the animation by setting an appropriate value for the transitionSpeed property.

After the gradients start animating, they will have to come to an end at one point or another. You can specify if the gradient should then just stop there or start animating again from the beginning using the loop property. This is set to true by default, which means that the gradient would keep animating.

Each color in a gradient can have a different opacity, which can be specified using the opacity property. This property accepts an array to determine how opaque each color is going to be. For two gradient colors, the value can be [0.1, 0.8]. For three gradient colors, the value can be [1, 0.5, 0.75], etc.

You also have the option to specify the time it takes for the gradient animation to go from one state to another using the stateTransitionSpeed. This is different from the transitionSpeed property, which controls the animation speed inside the same state.

In the following code snippet, I have created two different Granim instances to draw different gradients. In the first case, we have only specified a single gradient, so there is not any actual animation and the colors don’t change at all.

Animate Gradients Over an Image

Another common use of the Granim.js library would be to animate a gradient over an image drawn on the canvas. You can specify different properties to control how the image is drawn on the canvas using the image property. It accepts an object with key-value pairs as its value. You can use the source property to specify the path from which the library should get the image to draw it on the canvas.

Any image that you draw on the canvas will be drawn so that its center coincides with the center of the canvas. However, you can use the position property to specify a different position to draw the image. This property accepts an array of two elements as its value. The first element can have the values left, center, and right. The second element can have the values top, center, and bottom

These properties are generally useful when you know that the size of the canvas and the image won’t match. In these situations, you can use this property to specify the part of the image that should appear on the canvas.

If the images and the canvas have different dimensions, you can also stretch the image so that it fits properly inside the canvas. The stretchMode property also accepts an array of two elements as its value. Three valid values for both these elements are stretch, stretch-if-smaller, and stretch-if-larger.

A gradient with blend mode set to normal will completely hide the image underneath it. The only way to show an image below a gradient of solid colors would be to choose a different blend mode. You can read about all the possible blend mode values for a canvas on MDN.

I would like to point out that the ability to animate a gradient over an image was only added in version 1.1 of the Granim.js library. So you will have to use any version higher than that if you want this feature to work properly.

Methods to Control Gradient Animation Playback

Up to this point, we did not have any control over the playback of the gradient animation once it was instantiated. We could not pause/play it or change its state, direction, etc. The Granim.js library has different methods which let you accomplish all these tasks with ease.

You can play or pause any animation using the play() and pause() methods. Similarly, you can change the state of the gradient animation using the changeState('state-name') method. The state-name here has to be one of the state names that you defined when instantiating the Granim instance.

More methods were added in version 1.1 which allow you to change the direction and blend mode of an animation on the fly using the changeDirection('direction-name') and changeBlendingMode('blending-mode-name') methods.

In the following code snippet, I am using a button click event to call all these methods, but you can use any other event to call them.

Final Thoughts

In this tutorial, I have covered the basics of the Granim.js library so that you can get started with it as quickly as possible. There are a few other methods and properties that you might find useful when creating these gradient animations. You should read the official documentation in order to read about them all.

If you’re looking for additional JavaScript resources to study or to use in your work, check out what we have available in the Envato Market.

If you have any questions related to this tutorial, feel free to let me know in the comments.


Source: Nettuts Web Development

How to Build Complex, Large-Scale Vue.js Apps With Vuex

It’s so easy to learn and use Vue.js that anyone can build a simple application with that framework. Even novices, with the help of Vue’s documentation, can do the job. However, when complexity comes into play the things get a bit more serious. The truth is that multiple, deeply nested components with shared state can quickly turn your application into an unmaintainable mess.

The main problem in a complex application is how to manage the state between components without writing spaghetti code or producing side effects. In this tutorial you’ll learn how to solve that problem by using Vuex: a state management library for building complex Vue.js applications.

What is Vuex?

Vuex is a state management library specifically tuned for building complex, large-scale Vue.js applications. It uses a global, centralized store for all the components in an application taking advantage of its reactivity system for instant updates.

The Vuex store is designed in such a way that it is not possible to change its state from any component. This ensures that the state can only be mutated in a predictable manner. Thus your store becomes a single source of truth: every data element is only stored once and is read-only to prevent the application’s components from corrupting the state that is accessed by other components.

Why Do You Need Vuex?

You may ask: Why I need Vuex at first place? Can I just put the shared state in a regular JavaScript file and import it in my Vue.js application?

You can, of course, but compared to a plain global object Vuex store has some significant advantages and benefits:

  • The Vuex store is reactive. Once components retrieve a state from it, they will reactively update their views every time the state changes.
  • Components cannot directly mutate the store’s state. The only way to change the store’s state is by explicitly committing mutations. This ensures every state change leaves a trackable record which makes the application easier to debug and test.
  • You can easily debug your application thanks to the Vuex integration with Vue’s DevTools extension.
  • The Vuex store gives you a bird’s eye view on how everything is connected and affected in your application.
  • It’s easier to maintain and synchronize the state between multiple components, even if component hierarchy changes.
  • Vuex makes direct cross-components communication possible.
  • If some component is destroyed, the state in Vuex store will remain intact.

Getting Started With Vuex

Before we get started I want to make clear several things: First, to follow along this tutorial you need to have a good understanding of Vue.js and its components system, or at least minimal experience with the framework. 

Also, the aim of this tutorial is not to show you how to build actual complex application; the aim is to focus your attention more on Vuex concepts and how you can use it to build complex applications. For that reason, I’m going to use very plain and simple examples without any redundant code. Once you fully grasp the Vuex concepts you will be able to apply them on any level of complexity.

Finally, I’ll be using ES2015 syntax. If you are not familiar with it, you can learn it here.

And now, let’s get started!

Setting Up a Vuex Project

The first step to get started with Vuex is to have Vue.js and Vuex installed on your machine. There are several ways to do that but we’ll use the easiest one. Just create an HTML file and put the needed CDN links:

I use some CSS to make the components look nicer, but you don’t need to worry about that CSS code. It only helps you to gain a visual notion about what is going on. Just copy and paste the following inside the <head> tag:

Now, let’s create some components to work with. Inside the <script> tag, right above the closing </body> tag, put the following Vue code:

Here, we have a Vue instance, a parent component, and two child components. Each component have a heading “Score:” where we’ll output the app state.

The last thing you need to do is to put a wrapping <div> with id="app" right after the opening <body>, and then place the parent component inside:

So, the preparation work is done. We’re ready to move on.

Exploring Vuex

State Management

In real life we deal with complexity by using strategies to organize and structure the content we want to use. We group related things together in different sections, categories, etc. Just as how in a book library, the books are categorized and put in different sections so that we can easily find what we are looking for. The same is true for Vuex. It arranges the application data and logic related to state in four groups or categories: state, getters, mutations, and actions.

State and mutations are the base for any Vuex store:

  • state is an object that holds the state of the application data.
  • mutations is also an object containing methods which affect the state.

Getters and actions are like logical projections of state and mutations:

  • getters contains methods used to abstract the access to the state, and to do some preprocessing jobs, if needed (data calculating, filtering, etc.)
  • actions are methods used to trigger mutations and execute asynchronous code.

Let’s explore the following diagram to make the things a bit clear:

Vuex State Management Workflow Diagram

In the left side, we have an example of Vuex store, which we’ll create later on in this tutorial. In the right side, we have a Vuex workflow diagram, which shows how the different Vuex elements work together and communicate each another.

In order to change the state, a particular Vue component must commit mutations (eg. this.$store.commit('increment', 3)), and then, those mutations change the state (score becomes 3). After that, the getters are automatically updated thanks to Vue’s reactive system and they render the updates in the component’s view (with this.$store.getters.score). 

Mutations cannot execute asynchronous code, because this would make it impossible to record and track the changes in debug tools like Vue DevTools. To use asynchronous logic you need to put it in actions. In this case a component first will dispatch actions (this.$store.dispatch('incrementScore', 3000)) where the asynchronous code is executed, and then those actions will commit mutations, which will mutate the state. 

Create a Vuex Store Skeleton

After we explored how Vuex work, let’s create the skeleton for our Vuex store. Put the following code above the ChildB component registration:

To provide global access to the Vuex store from every component we need to add the store property in the Vue instance:

Now, we can access the store from every component with this.$store variable.

So far, if you open the project with CodePen in the browser, you should see the following result.

App Skeleton

State Properties

The state object contains all of the shared data in your application. Of course, if needed, each component can have its own private state too.

Imagine that you want to build a game application and you need a variable to store the game’s score. So, you put it in the state object:

Now, you can access the state’s score directly. Let’s go back to the components and reuse the data from the store. In order to be able to reuse reactive data from the store’s state, you should use computed properties. So, let’s create a score() computed property in the parent component:

In parent component’s template put the {{ score }} expression:

And now, do the same for the two child components.

Vuex is so smart that it will do all the work for us to reactively updates the score property whenever the state changes. Try to change the score’s value and see how the result updates in all of the three components.

Creating Getters

It is, of course, good that you can reuse the this.$store.state keyword inside the components, as you saw above. But imagine the following scenarios:

  1. In a large-scale application, where multiple components access the state of the store by using this.$store.state.score, you decide to change the name of score. This means that you have to change the name of the variable inside each and every component that uses it! 
  2. You want to use a computed value of the state. For example, let’s say you want to give the players a bonus of 10 points when the score reaches 100 points. So, when the score hits 100 points, 10 points bonus are added. This means each component has to contain a function that reuses the score and increment it with ten. You will have repeated code in each component, which is not good at all!

Fortunately, Vuex offers a working solution to handle such situations. Imagine the centralized getter that accesses the store’s state and provides a getter function to each of the state’s items. If needed, this getter can apply some computation to the state’s item. And if you need to change the name of some of the state’s properties, you only change them in one place, in this getter. 

Let’s create a score() getter:

A getter receives the state as its first argument, and then uses it to access the state’s properties.

Note: Getters also receive getters as the second argument. You can use it to access the other getters in the store.

In all components, modify the score() computed property to use the score() getter instead of state’s score directly.

Now, if you decide to change the score to result you need to update it only in one place: in the score() getter. Try it out in this CodePen!

Creating Mutations

Mutations are the only way allowed to change the state. Triggering changes simply means committing mutations in component methods.

A mutation is pretty much an event handler function that is defined by name. Mutation handler functions receive a state as a first argument. You can pass an additional second argument too, which is called the payload for the mutation. 

Let’s create a increment() mutation:

Mutations cannot be called directly! To perform a mutation, you should call the commit() method with a name of the corresponding mutation and possible additional parameters. It might be just one, as is the step in our case, or they might be multiple wrapped in an object.

Let’s use the increment() mutation in the two child components by creating a method named changeScore():

We are committing a mutation instead of changing this.$store.state.score directly, because we want to explicitly track the change made by the mutation. This way we make our application logic more transparent, traceable and easy to reason about. In addition, it makes it possible to implement tools, like Vue DevTools or Vuetron, that can log all mutations, take state snapshots, and perform time-travel debugging.

Now, let’s put the changeScore() method into use. In each template of the two child components, create a button and add a click event listener to it:

When you click the button, the state will be incremented by three, and this change will be reflected in all components. Now we have effectively achieved direct cross-components communication, which is not possible with the Vue.js built-in “props down, events up” mechanism. Check it out in our CodePen example.

Creating Actions

An action is just a function that commit a mutation. It changes the state indirectly which allows for executing of asynchronous operations. 

Let’s create a incrementScore() action:

Actions get the context as first parameter, which contains all methods and properties from the store. Usually we just extract the parts we need by using ES2015 argument destructing. The commit method is one we need very often. Actions also get a second payload argument, just like mutations.

In the ChildB component modify the changeScore() method:

To call an action we use dispatch() method with a name of the corresponding action and additional parameters just as with mutations.

Now, the “Change Score” button from ChildA component will increment the score by three. The identical button from ChildB component will do the same, but after 3 seconds delay. In the first case we execute synchronous code and we use a mutation, but in the second case we execute asynchronous code and we need to use an action instead. See how it all works in our CodePen example.

Vuex Mapping Helpers

Vuex offers some useful helpers which can streamline the process of creating state, getters, mutations, and actions. Instead of writing those functions manually we can tell Vuex to create them for us. Let’s see how it works.

Instead of writing the score() computed property like this:

We just use the mapState() helper like this:

And the score() property is created automatically for us.

The same is true for the getters, mutations, and actions. 

To create the score() getter we use mapGetters() helper:

To create changeScore() method we use mapMutations() helper like this:

When used for mutations and actions with payload argument, we must pass that argument in the template where we define the event handler:

If we want changeScore() to use an action instead of a mutation we use mapActions() like this:

Again, we must define the delay in the event handler:

Note: All mapping helpers return an object. So, if we want to use them in combination with other local computed properties or methods we need to merge them into one object. Fortunately with the object spread operator (...)  we can do it without using any utility. 

In our CodePen you can see an example of how all mapping helpers are used in practice.

Making the Store More Modular

It seems that the problem with complexity constantly obstructs our way. We solved it before by creating Vuex store, where we made the state management and components communication easy. In that store we have everything in one place, easy to manipulate and easy to reason about. However, as our application grows this easy to manage store file becomes larger and larger, and, as a result, harder to maintain. Again, we need some strategies and techniques for improving the application structure by returning it to its easy to maintain form. In this section, we’ll explore several techniques which can help us in this undertaking.

Using Vuex Modules

Vuex allows us to split the store object into separate modules. Each module can contain its own state, mutations, actions, getters, and other nested modules. After we create the needed modules, we register them in the store.

Let’s see it in action:

In the above example, we created two modules, one for each child component. The modules are just plain objects, which we register as scoreBoard and resultBoard in the modules object inside the store. The code for childA is the same as that in the store from the previous examples. In the code for childB we add some changes in values and names.

Let’s now tweak ChildB component to reflect the changes in the resultBoard module. 

In ChildA component the only thing we need to modify is the changeScore() method:

As you can see, splitting the store into modules makes it much more lightweight and maintainable, while still keeps its great functionality. Check out the updated CodePen to see it in action.

Namespaced Modules

If you want or need to use one and the same name for particular property or method in your modules, then you should consider namespacing them. Otherwise you may observe some strange side effects, such as executing all the actions with same names, or getting the wrong state’s values. 

To namespace a Vuex module you just set the namespaced property to true.

In the above example we made the property and method names the same for the two modules. And now we can use a property or method prefixed with the name of the module. For example, if we want to use the score() getter from the resultBoard module, we type it like this: resultBoard/score. If we want the score() getter from the scoreBoard module, then we type it like this: scoreBoard/score

Let’s now modify our components to reflect the changes we made. 

As you can see in our CodePen example, we can now use the method or property we want and get the result we expect.

Splitting the Vuex Store Into Separate Files

In the previous section, we improved the application structure to some extent by separating the store into modules. We made the store cleaner and more organized, but still all of the store code and its modules lie in one and the same big file. 

So the next logical step is to split the Vuex store in separate files. The idea is to have an individual file for the store itself and one for each of its objects, including the modules. This means having separate files for the state, getters, mutations, actions, and for each individual module (store.jsstate.js, getters.js, etc.) You can see an example of this structure at the end of the next section.

Using Vue Single File Components

We’ve made the Vuex store as modular as we can. The next thing we can do is to apply the same strategy to the Vue.js components too. We can put each component in a single, self-contained file with a .vue extension. To learn how this works you can visit the Vue Single File Components documentation page

So, in our case, we’ll have three files: Parent.vueChildA.vue, and ChildB.vue

Finally, if we combine all three techniques we’ll end up with the following or similar structure:

In our tutorial GitHub repo you can see the completed project with the above structure.

Recap

Let’s recap some main points you need to remember about Vuex:

Vuex is a state management library, which help us to build complex, large-scale applications. It uses a global, centralized store for all the components in an application. To abstract the state we use getters. Getters are pretty much like computed properties and are ideal solution when we need to filter or calculate something on runtime.

Vuex store is reactive and components cannot directly mutate the store’s state. The only way to mutate the state is by commiting mutations, which are synchronous transactions. Each mutation should perform only one action, must be as simple as possible, and only responsible for updating just a piece of state.

Asynchronous logic should be encapsulated in actions. Each action can commit one or more mutations, and one mutation can be committed by more than one action. Actions can be complex but they never change the state directly.

Finally, modularity is the key to maintainability. To deal with complexity and make our code modular we use the “divide and conquer” principle and the code splitting technique.

Conclusion

So folks, that’s it. You already know the main concepts behind Vuex and you are ready to start applying them in practice.  

For the sake of brevity and simplicity, I omitted intentionally some details and features of Vuex, so you’ll need to read the full Vuex documentation to learn everything about Vuex and its feature set.


Source: Nettuts Web Development

Creating Stylish and Responsive Progress Bars Using ProgressBar.js

Nothing on the web happens instantly. The only difference is in the time it takes for a process to complete. Some processes can happen in a few milliseconds, while others can take up to several seconds or minutes. For example, you might be editing a very large image uploaded by your users, and this process can take some time. In such cases, it is a good idea to let the visitors know that the website is not stuck somewhere but it is actually working on your image and making some progress.

One of the most common ways to show readers how much a process has progressed is to use progress bars. In this tutorial, you will learn how to use the ProgressBar.js library to create different progress bars with simple and complex shapes.

Creating a Basic Progress Bar

Once you have included the library in your project, creating a progress bar using this library is easy. ProgressBar.js is supported in all major browsers, including IE9+, which means that you can use it in any website you are creating with confidence. You can get the latest version of the library from GitHub or directly use a CDN link to add it in your project.

To avoid any unexpected behavior, please make sure that the container of the progress bar has the same aspect ratio as the progress bar. In the case of a circle, the aspect ratio of the container should be 1:1 because the width will be equal to the height. In the case of a semicircle, the aspect ratio of the container should be 2:1 because the width will be double the height. Similarly, in the case of a simple line, the container should have an aspect ratio of 100:strokeWidth for the line.

When creating progress bars with a line, circle, or semicircle, you can simply use the ProgressBar.Shape() method to create the progress bar. In this case, the Shape can be a Circle, Line, or SemiCircle. You can pass two parameters to the Shape() method. The first parameter is a selector or DOM node to identify the container of the progress bar. The second parameter is an object with key-value pairs which determine the appearance of the progress bar.

You can specify the color of the progress bar using the color property. Any progress bar that you create will have a dark gray color by default. The thickness of the progress bar can be specified using the strokeWidth property. You should keep in mind that the width here is not in pixels but in terms of a percentage of the canvas size. For instance, if the canvas is 200px wide, a strokeWidth value of 5 will create a line which is 10px thick.

Besides the main progress bar, the library also allows you to draw a trailing line which will show readers the path on which the progress bar will move. The color of the trail line can be specified using the trailColor property, and its width can be specified using the trailWidth property. Just like strokeWidth, the trailWidth property also computes the width in percentage terms.

The total time taken by the progress bar to go from its initial state to its final state can be specified using the duration property. By default, a progress bar will complete its animation in 800 milliseconds.

You can use the easing property to specify how a progress bar should move during the animation. All progress bars will move with a linear speed by default. To make the animation more appealing, you can set this value to something else like easeIn, easeOut, easeInOut, or bounce.

After specifying the initial parameter values, you can animate the progress bars using the animate() method. This parameter accepts three parameters. The first parameter is the amount up to which you want to animate the progress line. The two other parameters are optional. The second parameter can be used to override any animation property values that you set during initialization. The third parameter is a callback function to do something else once the animation ends.

In the following example, I have created three different progress bars using all the properties we have discussed so far.

Animating Text Values With the Progress Bar

The only thing that changes with the animation of the progress bars in the above example is their length. However, ProgressBar.js also allows you to change other physical attributes like the width and color of the stroking line. In such cases, you will have to specify the initial values for the progress bar inside the from parameter and the final values inside the to parameter when initializing the progress bars.

You can also tell the library to create an accompanying text element with the progress bar to show some textual information to your users. The text can be anything from a static value to a numerical value indicating the progress of the animation. The text parameter will accept an object as its value. 

This object can have a value parameter to specify the initial text to be shown inside the element. You can also provide a class name to be added to the text element using the className parameter. If you want to apply some inline styles to the text element, you can specify them all as a value of the style parameter. All the default styles can be removed by setting the value of style to null. It is important to remember that the default values only apply if you have not set a custom value for any CSS property inside style.

The value inside the text element will stay the same during the whole animation if you don’t update it yourself. Luckily, ProgressBar.js also provides a step parameter which can be used to define a function to be called with each animation step. Since this function will be called multiple times each second, you need to be careful with its use and keep the calculations inside it simple.

Creating Progress Bars With Custom Shapes

Sometimes, you might want to create progress bars with different shapes that match the overall theme of your website. ProgressBar.js allows you to create progress bars with custom shapes using the Path() method. This method works like Shape() but provides fewer parameters to customize the progress bar animation. You can still provide a duration and easing value for the animation. If you want to animate the color and width of the stroke used for drawing the custom path, you can do so inside the from and to parameters.

The library does not provide any way to draw a trail for the custom path, as it did for simple lines and circles. However, you can create the trail yourself fairly easily. In the following example, I have created a triangular progress bar using the Path() method.

Before writing the JavaScript code, we will have to define our custom SVG path in HTML. Here is the code I used to create a simple triangle:

You might have noticed that I created two different path elements. The first path has a light gray color which acts like the trail we saw with simple progress bars in the previous section. The second path is the one that we animate with our code. We have given it an id which is used to identify it in the JavaScript code below.

Final Thoughts

As you saw in this tutorial, ProgressBar.js allows you to easily create different kinds of progress bars with ease. It also gives you the option to animate different attributes of the progress bar like its width and color. 

Not only that, but you can also use this library to change the value of an accompanying text element in order to show the progress in textual form. This tutorial covers everything that you need to know to create simple progress bars. However, you can go through the documentation to learn more about the library.

If there is anything that you would like me to clarify in this tutorial, feel free to let me know in the comments.


Source: Nettuts Web Development

Set Up an OAuth2 Server Using Passport in Laravel

In this article, we’re going to explore how you could set up a fully fledged OAuth2 server in Laravel using the Laravel Passport library. We’ll go through the necessary server configurations along with a real-world example to demonstrate how you could consume OAuth2 APIs.

I assume that you’re familiar with the basic OAuth2 concepts and flow as we’re going to discuss them in the context of Laravel. In fact, the Laravel Passport library makes it pretty easy to quickly set up an OAuth2 server in your application. Thus, other third-party applications are able to consume APIs provided by your application.

In the first half of the article, we’ll install and configure the necessary libraries, and the second half goes through how to set up demo resources in your application and consume them from third-party applications.

Server Configurations

In this section, we’re going to install the dependencies that are required in order to make the Passport library work with Laravel. After installation, there’s quite a bit of configuration that we’ll need to go through so that Laravel can detect the Passport library.

Let’s go ahead and install the Passport library using composer.

That’s pretty much it as far as the Passport library installation is concerned. Now let’s make sure that Laravel knows about it.

Working with Laravel, you’re probably aware of the concept of a service provider that allows you to configure services in your application. Thus, whenever you want to enable a new service in your Laravel application, you just need to add an associated service provider entry in the config/app.php.

If you’re not aware of Laravel service providers yet, I would strongly recommend that you do yourself a favor and go through this introductory article that explains the basics of service providers in Laravel.

In our case, we just need to add the PassportServiceProvider provider to the list of service providers in config/app.php as shown in the following snippet.

Next, we need to run the migrate artisan command, which creates the necessary tables in a database for the Passport library.

To be precise, it creates following the tables in the database.

Next, we need to generate a pair of public and private keys that will be used by the Passport library for encryption. As expected, the Passport library provides an artisan command to create it easily.

That should have created keys at storage/oauth-public.key and storage/oauth-private.key. It also creates some demo client credentials that we’ll get back to later.

Moving ahead, let’s oauthify the existing User model class that Laravel uses for authentication. To do that, we need to add the HasApiTokens trait to the User model class. Let’s do that as shown in the following snippet.

The HasApiTokens trait contains helper methods that are used to validate tokens in the request and check the scope of resources being requested in the context of the currently authenticated user.

Further, we need to register the routes provided by the Passport library with our Laravel application. These routes will be used for standard OAuth2 operations like authorization, requesting access tokens, and the like.

In the boot method of the app/Providers/AuthServiceProvider.php file, let’s register the routes of the Passport library.

Last but not least, we need to change the api driver from token to passport in the config/auth.php file, as we’re going to use the Passport library for the API authentication.

So far, we’ve done everything that’s required as far as the OAuth2 server configuration is concerned.

Set Up the Demo Resources

In the previous section, we did all the hard work to set up the OAuth2 authentication server in our application. In this section, we’ll set up a demo resource that could be requested over the API call.

We will try to keep things simple. Our demo resource returns the user information provided that there’s a valid uid parameter present in the GET request.

Let’s create a controller file app/Http/Controllers/UserController.php with the following contents.

As usual, you need to add an associated route as well, which you are supposed to add in the routes/web.php file. But what we are talking about is the API route, and thus it needs special treatment.

The API routes are defined in the routes/api.php file. So, let’s go ahead and add our custom API route as shown in the following snippet.

Although we’ve defined it as /user/get, the effective API route is /api/user/get, and that’s what you should use when you request a resource over that route. The api prefix is automatically handled by Laravel, and you don’t need to worry about that!

In the next and last section, we’ll discuss how you could create client credentials and consume the OAuth2 API.

How to Consume OAuth2 APIs

Now that we’ve set up the OAuth2 server in our application, any third party can connect to our server with OAuth and consume the APIs available in our application.

First of all, third-party applications must register with our application in order to be able to consume APIs. In other words, they are considered as client applications, and they will receive a client id and client secret upon registration.

The Passport library provides an artisan command to create client accounts without much hassle. Let’s go ahead and create a demo client account.

When you run the artisan passport:client command, it asks you a few questions before creating the client account. Out of those, there’s an important one that asks you the callback URL.

The callback URL is the one where users will be redirected back to the third-party end after authorization. And that’s where the authorization code that is supposed to be used in exchange for the access token will be sent. We are about to create that file in a moment.

Now, we’re ready to test OAuth2 APIs in the Laravel application.

For demonstration purposes, I’ll create the oauth2_client directory under the document root in the first place. Ideally, these files will be located at the third-party end that wants to consume APIs in our Laravel application.

Let’s create the oauth2_client/auth_redirection.php file with the following contents.

Make sure to change the client_id and redirect_uri parameters to reflect your own settings—the ones that you used while creating the demo client account.

Next, let’s create the oauth2_client/callback.php file with the following contents.

Again, make sure to adjust the URLs and client credentials according to your setup in the above file.

How It Works Altogether

In this section, we’ll test it altogether from the perspective of an end user. As an end user, there are two applications in front of you:

  1. The first one is the Laravel application that you already have an account with. It holds your information that you could share with other third-party applications.
  2. The second one is the demo third-party client application, auth_redirection.php and callback.php, that wants to fetch your information from the Laravel application using the OAuth API.

The flow starts from the third-party client application. Go ahead and open the http://localhost/oauth2_client/auth_redirection.php URL in your browser, and that should redirect you to the Laravel application. If you’re not already logged into the Laravel application, the application will ask you to do so in the first place.

Once the user is logged in, the application displays the authorization page.

If the user authorizes that request, the user will be redirected back to the third-party client application at http://localhost/oauth2_client/callback.php along with the code as the GET parameter that contains the authorization code.

Once the third-party application receives the authorization code, it could exchange that code with the Laravel application to get the access token. And that’s exactly what it has done in the following snippet of the oauth2_client/callback.php file.

Next, the third-party application checks the response of the CURL request to see if it contains a valid access token in the first place.

As soon as the third-party application gets the access token, it could use that token to make further API calls to request resources as needed from the Laravel application. Of course, the access token needs to be passed in every request that’s requesting resources from the Laravel application.

We’ve tried to mimic the use-case in that the third-party application wants to access the user information from the Laravel application. And we’ve already built an API endpoint, http://your-laravel-site-url/api/user/get, in the Laravel application that facilitates it.

So that’s the complete flow of how you’re supposed to consume the OAuth2 APIs in Laravel.

And with that, we’ve reached the end of this article.

Conclusion

Today, we explored the Passport library in Laravel, which allows us to set up an OAuth2 server in an application very easily. 

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.

Don’t hesitate to share your thoughts and queries using the feed below!


Source: Nettuts Web Development

Getting Started with Redux: Connecting Redux with React

This is the third part of the series on Getting Started with Redux and in this tutorial, we’re going to learn how to connect a Redux store with React.  Redux is an independent library that works with all the popular front-end libraries & frameworks. And it works flawlessly with React because of its functional approach.

You don’t need to have followed the previous parts of this series for this tutorial to make sense. If you’re here to learn about using React with Redux, you can take the Quick Recap below and then check out the code from the previous part and start from there. 

Quick Recap

In the first post, we learned about the Redux workflow and answered the question, Why Redux?. We created a very basic demo application and showed you how the various components of Redux—actions, reducers, and the store— are connected.

In the previous post, we started building a contact list application that lets you add contacts and then displays them as a list. A Redux store was created for our contact list and we added a few reducers and actions. We attempted to dispatch actions and retrieve the new state using store methods like store.dispatch() and store.getState().

By the end of this article, you’ll learn

  1. the difference between container components and presentational components
  2. about the react-redux library
  3. how to bind react and redux using connect()
  4. how to dispatch actions using mapDispatchToProps
  5. how to retrieve state using mapStateToProps

The code for the tutorial is available on GitHub at the react-redux-demo repo. Grab the code from the v2 branch and use that as a starting point for this tutorial. If you’re curious to know how the application looks by the end of this tutorial, try the v3 branch. Let’s get started.

Designing a Component Hierarchy: Smart vs. Dumb Component

This is a concept that you’ve probably heard of before. But let’s have a quick look at the difference between smart and dumb components. Recall that we had created two separate directories for components, one named containers/, and the other components/. The benefit of this approach is that the behavior logic is separated from the view.

The presentational components are said to be dumb because they are concerned about how things look. They are decoupled from the business logic of the application and receive data and callbacks from a parent component exclusively via props. They don’t care if your application is connected to a Redux store if the data is coming from the local state of the parent component. 

The container components, on the other hand, deal with the behavioral part and should contain very limited DOM markup and style. They pass the data that needs to be rendered to the dumb components as props. 

I’ve covered the topic in-depth in another tutorial, Stateful vs. Stateless Components in React.

Moving on, let’s see how we’re going to organize our components.

Designing component Hierarchy

Presentational Components

Here are the presentational components that we’ll be using in this tutorial. 

components/AddContactForm.jsx

This is an HTML form for adding a new contact. The component receives onInputChange and onFormSubmit callback as props. The onInputChange event is triggered when the input value changes and onFormSubmit when the form is being submitted.

components/ContactList.jsx

This component receives an array of contact objects as props and hence the name ContactList. We use the Array.map() method to extract individual contact details and then pass on that data to <ContactCard />.

components/ContactCard.jsx

This component receives a contact object and displays the contact’s name and image. For practical applications, it might make sense to host JavaScript images in the cloud.

Container Components

We’re also going to construct barebones container components.

containers/Contacts.jsx

The returnContactList() function retrieves the array of contact objects and passes it to the ContactList component. Since returnContactList() retrieves the data from the store, we’ll leave that logic blank for the moment.

containers/AddContacts.jsx

We’ve created three barebones handler method that corresponds to the three actions. They all dispatch actions to update the state. In the render method, we’ve left out the logic for showing/hiding the form because we need to fetch the state. 

Now let’s see how to bind react and redux together

The react-redux Library

React bindings are not available in Redux by default. You will need to install an extra library called react-redux first. 

The library exports just two APIs that you need to remember, a <Provider /> component and a higher-order function known as connect()

The Provider Component

Libraries like Redux need to make the store data accessible to the whole React component tree starting from the root component. The Provider pattern allows the library to pass the data from top to the bottom. The code below demonstrates how Provider magically adds the state to all the components in the component tree. 

Demo Code

The entire app needs to have access to the store. So, we wrap the provider around the app component and then add the data that we need to the tree’s context. The descendants of the component then have access to the data. 

The connect() Method 

Now that we’ve provided the store to our application, we need to connect the React to the store. The only way that you can communicate with the store is by dispatching actions and by retrieving the state. We’ve previously used store.dispatch() to dispatch actions and store.getState() to retrieve the latest snapshot of the state. The connect()lets you do exactly this, but with the help of two methods known as mapDispatchToProps and mapStateToProps. I have demonstrated this concept in the example below:

Demo Code

mapStateToProps and mapDispatchToProps both return an object and the key of this object becomes a prop of the connected component. For instance, state.contacts.newContact is mapped to props.newContact. The action creator addContact() is mapped to props.addContact.  

But for this to work, you need the last line in the code snippet above. 

Instead of exporting the AddContact component directly, we’re exporting a connected component. The connect provides addContact and newContact as props to the <AddContact/> component. 

How to Connect React and Redux?

Next, we’re going to cover the steps that you need to follow to connect React and Redux.

Install the react-redux Library

Install the react-redux library if you haven’t already. You can use NPM or Yarn to install it. 

Provide the Store to your App Component

Create the store first. Then, make the store object accessible to your component tree by passing it as a prop to <Provider />.

index.js

Connect React Containers to Redux

The connect function is used to bind React container to Redux. What that means is that you can use the connect feature to:

  1. subscribe to the store and map its state to your props
  2. dispatch actions and map the dispatch callbacks into your props

Once you’ve connected your application to Redux, you can use this.props to access the current state and also to dispatch actions. I am going to demonstrate the process on theAddContact component. AddContact needs to dispatch three actions and get the state of two properties from the store. Let’s have a look at the code.

First, import connect into AddContact.jsx.

Second, create two methods mapStateToProps and mapDispatchToProps.

mapStateToProps receives the state of the store as an argument. It returns an object that describes how the state of the store is mapped into your props. mapDispatchToProps returns a similar object that describes how the dispatch actions are mapped to your props. 

Finally, we use connect to bind the AddContact component to the two functions as follows:

Update the Container Components to Use the Props

The component’s props are now equipped to read state from the store and dispatch actions. The logic for handeInputChange, handleSubmit and showAddContactBox should be updated as follows:

We’ve defined the handler methods. But there is still one part missing—the conditional statement inside the render function.

If isHidden is false, the form is rendered. Otherwise,a button gets rendered. 

Displaying The Contacts

We’ve completed the most challenging part. Now, all that’s left is to display these contacts as a list. The Contacts container is the best place for that logic. 

We’ve gone through the same procedure that we followed above to connect the Contacts component with the Redux store. The mapStateToProps function maps the store object to the contactList props. We then use connect to bind the props value to the Contact component. The second argument to the connect is null because we don’t have any actions to be dispatched. That completes the integration of our app with the state of the Redux store. 

What Next?

In the next post, we’ll take a deeper look at middlewares and start dispatching actions that involve fetching data from the server. Share your thoughts in the comments!


Source: Nettuts Web Development

Getting Started With Redux: Learn by Example

Redux helps you manage state by setting the state up at a global level. In the previous tutorial, we had a good look at the Redux architecture and the integral components of Redux such as actions, action creators, the store, and reducers. 

In this second post of the series, we are going to bolster our understanding of Redux and build on top of what we already know. We will start by creating a realistic Redux application—a contact list—that’s more complex than a basic counter. This will help you strengthen your understanding of the single store and multiple reducers concept which I introduced in the previous tutorial. Then later we’ll talk about binding your Redux state with a React application and the best practices that you should consider while creating a project from scratch. 

However, it’s okay if you haven’t read the first post—you should still be able to follow along as long as you know the Redux basics. The code for the tutorial is available in the repo, and you can use that as a starting point. 

Creating a Contact List Using Redux

We’re going to build a basic contact list with the following features:

  • display all contacts
  • search for contacts
  • fetch all contacts from the server
  • add a new contact
  • push the new contact data into the server

Here’s what our application is going to look like:

Getting Started With Redux  Final View of the Contact List
Final product — Contact list View

Getting Started With Redux  Final View of the Contact Form
Final Product — Add contact view

Covering everything in one stretch is hard. So in this post we’re going to focus on just the Redux part of adding a new contact and displaying the newly added contact. From a Redux perspective, we’ll be initializing the state, creating the store, adding reducers and actions, etc. 

In the next tutorial, we’ll learn how to connect React and Redux and dispatch Redux actions from a React front-end. In the final part, we’ll shift our focus towards making API calls using Redux. This includes fetching the contacts from the server and making a server request while adding new contacts. Apart from that, we’ll also create a search bar feature that lets you search all the existing contacts. 

Create a Sketch of the State Tree

You can download the react-redux demo application from my GitHub repository. Clone the repo and use the v1 branch as a starting point. The v1 branch is very similar to the create-react-app template. The only difference is that I’ve added a few empty directories to organise Redux. Here’s the directory structure.

Alternatively, you can create a new project from scratch. Either way, you will need to have installed a basic react boilerplate and redux before you can get started. 

It’s a good idea to have a rough sketch of the state tree first. In my opinion, this will save you lots of time in the long run. Here’s a rough sketch of the possible state tree. 

Our store needs to have two properties—contacts and ui. The contacts property takes care of all contacts-related state, whereas the ui handles UI-specific state. There is no hard rule in Redux that prevents you from placing the ui object as a sub-state of contacts. Feel free to organize your state in a way that feels meaningful to your application. 

The contacts property has two properties nested inside it—contactlist and newContact. The contactlist is an array of contacts, whereas newContact temporarily stores contact details while the contact form is being filled. I am going to use this as a starting point for building our awesome contact list app. 

How to Organize Redux

Redux doesn’t have an opinion about how you structure your application. There are a few popular patterns out there, and in this tutorial, I will briefly talk about some of them. But you should pick one pattern and stick with it until you fully understand how all the pieces are connected together.

The most common pattern that you’ll find is the Rails-style file and folder structure. You’ll have several top-level directories like the ones below:

  • components: A place to store the dumb React components. These components do not care whether you’re using Redux or not.
  • containers: A directory for the smart React components that dispatch actions to the Redux store. The binding between redux and react will be taking place here. 
  • actions: The action creators will go inside this directory. 
  • reducers: Each reducer gets an individual file, and you’ll be placing all the reducer logic in this directory.
  • store: The logic for initializing the state and configuring the store will go here. 

The image below demonstrates how our application might look if we follow this pattern:

Organising Folder structure in Redux

The Rails style should work for small and mid-sized applications. However, when your app grows, you can consider moving towards the domain-style approach or other popular alternatives that are closely related to domain-style. Here, each feature will have a directory of its own, and everything related to that feature (domain) will be inside it. The image below compares the two approaches, Rails-style on the left and domain-style on the right. 

Comparison of two popular techniques for organising Redux and React

For now, go ahead and create directories for components, containers, store, reducers, and action. Let’s start with the store. 

Single Store, Multiple Reducers

Let’s create a prototype for the store and the reducer first. From our previous example, this is how our store would look: 

The switch statement has three cases that correspond to three actions that we will be creating. Here is a brief explanation of what the actions are meant for. 

  • HANDLE_INPUT_CHANGE: This action gets triggered when the user inputs new values into the contact form.
  • ADD_NEW_CONTACT: This action gets dispatched when the user submits the form.
  • TOGGLE_CONTACT_FORM: This is a UI action that takes care of showing/hiding the contact form. 

Although this naive approach works, as the application grows, using this technique will have a few shortcomings.

  1. We’re using a single reducer. Although a single reducer sounds okay for now, imagine having all your business logic under one very large reducer.  
  2. The code above doesn’t follow the Redux structure that we’ve discussed in the previous section.

To fix the single reducer issue, Redux has a method called combineReducers that lets you create multiple reducers and then combine them into a single reducing function. The combineReducers function enhances readability. So I am going to split the reducer into two—a contactsReducer and a uiReducer

In the example above, createStore accepts an optional second argument which is the initial state. However, if we are going to split the reducers, we can move the whole initialState to a new file location, say reducers/initialState.js. We will then import a subset of initialState into each reducer file. 

Splitting the Reducer 

Let’s restructure our code to fix both the issues. First, create a new file called store/createStore.js and add the following code:

Next, create a root reducer in reducers/index.js as follows:

Finally, we need to create the code for the contactsReducer and uiReducer.

reducers/contactsReducer.js

reducers/uiReducer.js

When you’re creating reducers, always keep the following in mind: a reducer needs to have a default value for its state, and it always needs to return something. If the reducer fails to follow this specification, you will get errors.

Since we’ve covered a lot of code, let’s have a look at the changes that we’ve made with our approach:

  1. The combineReducers call has been introduced to tie together the split reducers.
  2. The state of the ui object will be handled by uiReducer and the state of the contacts by the contactsReducer
  3. To keep the reducers pure, spread operators have been used. The three dot syntax is part of the spread operator. If you’re not comfortable with the spread syntax, you should consider using a library like Immutability.js.
  4. The initial value is no longer specified as an optional argument to createStore. Instead, we’ve created a separate file for it called initialState.js. We’re importing initialState and then setting the default state by doing state = initialState.ui

State Initialization

Here’s the code for the reducers/initialState.js file.

Actions and Action Creators

Let’s add a couple of actions and action creators for adding handling form changes, adding a new contact, and toggling the UI state. If you recall, action creators are just functions that return an action. Add the following code in actions/index.js.

Each action needs to return a type property. The type is like a key that determines which reducer gets invoked and how the state gets updated in response to that action. The payload is optional, and you can actually call it anything you want. 

In our case, we’ve created three actions.

The TOGGLE_CONTACT_FORM doesn’t need a payload because every time the action is triggered, the value of ui.isContactFormHidden gets toggled. Boolean-valued actions do not require a payload. 

The HANDLE_INPUT_CHANGE action is triggered when the form value changes. So, for instance, imagine that the user is filling the email field. The action then receives "email" and "bob@example.com" as inputs, and the payload handed over to the reducer is an object that looks like this:

The reducer uses this information to update the relevant properties of the newContact state. 

Dispatching Actions and Subscribing to the Store

The next logical step is to dispatch the actions. Once the actions are dispatched, the state changes in response to that. To dispatch actions and to get the updated state tree, Redux offers certain store actions. They are:

  • dispatch(action): Dispatches an action that could potentially trigger a state change. 
  • getState(): Returns the current state tree of your application.
  • subscriber(listener): A change listener that gets called every time an action is dispatched and some part of the state tree is changed. 

Head to the index.js file and import the configureStore function and the three actions that we created earlier:

Next, create a store object and add a listener that logs the state tree every time an action is dispatched:

Finally, dispatch some actions:

If everything is working right, you should see this in the developer console.

Redux store being logged in developer console

That’s it! In the developer console, you can see the Redux store being logged, so you can see how it changes after each action.

Summary

We’ve created a bare-bones Redux application for our awesome contact list application. We learned about reducers, splitting reducers to make our app structure cleaner, and writing actions for mutating the store. 

Towards the end of the post, we subscribed to the store using the store.subscribe() method. Technically, this isn’t the best way to get things done if you’re going to use React with Redux. There are more optimized ways to connect the react front-end with Redux. We’ll cover those in the next tutorial.  


Source: Nettuts Web Development

Introduction to API Calls With React and Axios

This tutorial will teach you how to use Axios to fetch data and then how to manipulate it and eventually display it on your page with filtering functionality. You will learn how to use the map, filter and includes methods along the way. On top of that, you will be creating a Higher-Order Component (HOC) to handle the loading state of the fetched data from the API endpoint.

Let’s start with a clean React app. I assume you use create-react-app, and the filenames will be in accordance with its outputs.

We only need to install the Axios module for this tutorial.

Go to your project directory through the terminal window and then type in npm install axios -save in order to install Axios for your project locally.

Fetching the Data

We will be using the Random User Generator API to fetch random user information to use in our application.

Let’s add the Axios module to our application by importing it into our App.js file.

The Random User Generator API offers a bunch of options for creating various types of data. You can check the documentation for further information, but for this tutorial, we will keep it simple.

We want to fetch ten different users, and we only need the name, surname, and a unique ID, which is required for React when creating lists of elements. Also, to make the call a bit more specific, let’s include the nationality option as an example.

Below is the API that we will make a call for.

Note that I didn’t use the id option provided in the API due to the fact that it sometimes returns null for some users. So, just to make sure that there will be a unique value for each user, I included the registered option in the API.

https://randomuser.me/api/?results=10&inc=name,registered&nat=fr

You can copy and paste it into your browser and you will see the returned data in JSON format.

Now, the next thing is to make an API call through Axios.

First of all, let’s create a state so that we can store the fetched data.

Inside our App component, add a class constructor and then create the state.

Here you see users and store states. One will be used for filtering purposes and will not be edited, and the other one will hold the filter results that will be shown in the DOM.

Now go ahead and create the componentDidMount() lifecycle hook.

Inside this lifecycle hook, we will fetch the data, and then by using the map method, we will create new intermediate data that we will use inside the setState method.

If you check the result of the API call in your browser, you will see that there are first and last key-value pairs inside the name object but no key-value pair for a full name. So we will be combining first and last to create a full name inside a new JavaScript Object. Note that JSON and JavaScript Object are different things, although they basically work the same way.

Let’s move step by step.

Add the following code to your App component.

When you check the console, you will see an object output. If you open up this object, there is another object inside it named data, and inside data, there is an array named results.

Let’s further change the console.log(json).

Here we reached the name of the first value inside the results array.

Now let’s use the built-in map method of JavaScript in order to iterate through each element inside the array and create a new array of JavaScript Objects with a new structure.

Here, we called the map method on json.data.results, which is an array, and then referred each element of the array as result (notice the singular/plural difference). Then, by using the key-value pair of each object inside the array, we created another object with name and id key-value pairs.

At the end, we used another then method in order to be able to refer to our new data. We referred it as newData, and then we just logged to the console to see if everything went as planned.

You should see a new array with objects having name and id pairs.

Storing the Data

Instead of logging the result to the console, we have to store it. In order to do that, we will use setState.

Here, we initially set both users and store data with our new newData array.

We need two variables due to the fact that we need to store the original data and should never lose it. By using the information inside the store state, we can filter the data and then populate the users state and show it on the page. This will be clearer when we implement the filtering functionality.

Last but not least, we added catch to actually catch any possible errors during fetching and display the error as an alert message.

Filtering Functionality

The idea of filtering is quite simple. We have our store state, and it always keeps the original data without changing. Then, by using the filter function on this state, we only get the matching elements and then assign them to the users state.

The filter method requires a function as an argument, a function to be run for each element in the array. Here we refer each element inside the array as item. Then we take the name key of each item and convert it to lower case in order to make our filtering functionality case insensitive. 

After we have the name key for the item, we check if this one includes the search string we typed in. includes is another built-in JavaScript method. We pass the search string typed in the input field as an argument to includes, and it returns if this string is included in the variable it was called on. Again, we convert the input string to lower case so that it does not matter whether you type upper or lower case inputs. 

In the end, the filter method returns the matching elements. So we simply take these elements and store them inside the users state through setState.

Below you can find the final version of the function we created.

Creating the Components

Although for this small example we could put everything inside the App component, let’s take advantage of React and make some small functional/stateless components.

Let’s add the following structure to the render method of the App component.

For the time being, we will be just focusing on the functionality. Later, I will provide the CSS file I have created.

Notice that we have the searchFunc prop for the SearchBar component and the usernames prop for the List component.

Note that we use the users state instead of the store state to show the data because the users state is the one containing the filtered results.

The SearchBar Component

This component is quite straightforward. It only takes the filterNames function as a prop and calls this function when the input field changes.

The List Component

This one will simply list the names of the users.

Here, we again used the map method to get each item in the array and create a <li> item out of it. Note that when you use map to create a list of items, you need to use a key in order for React to keep track of each list item.

Notice that we wrapped List with another component named LoadingHOC before exporting it. This is how Higher-Order Components (HOCs) work. 

What we did here is to pass our component as an argument to another component before exporting it. So this LoadingHOC component will be enhancing our component with new features.

The LoadingHOC Component

As I briefly explained before, a HOC takes a component as an input and then exports an enhanced version of the input component.

Inside the HOC, we can directly access the props of the input component. So we just check whether the length of the usernames prop is 0 or not. If it is 0, this means that the data has yet to be fetched because it is an empty array by default. So we just show a spinner GIF that we imported. Otherwise, we just show the input component itself.

It’s imported in order not to forget to pass any props and states back to the input component with a spread operator. Otherwise, your component would be deprived of them.

CSS File

Below you can find the CSS file specific to this example.

Conclusion

Throughout this tutorial, we took a quick look at the Random User Generator API as a source of random data. Then we fetched the data from an API endpoint and restructured the results inside a new JavaScript Object with the map method.

The next thing was to create a filtering function with the filter and includes methods. Finally, we created two different components and enhanced one of them with a Higher-Order Component (HOC) by introducing a loading indicator when the data is not there yet.

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in Envato Market that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.


Source: Nettuts Web Development

A Beginner’s Guide to Regular Expressions in JavaScript

Everyone working with JavaScript will have to deal with strings at one point or other. Sometimes, you will just have to store a string inside another variable and then pass it over. Other times, you will have to inspect it and see if it contains a particular substring.

However, things are not always this easy. There will be times when you will not be looking for a particular substring but a set of substrings which follow a certain pattern.

Let’s say you have to replace all occurrences of “Apples” in a string with “apples”. You could simply use theMainString.replace("Apples", "apples"). Nice and easy.

Now let’s say you have to replace “appLes” with “apples” as well. Similarly, “appLES” should become “apples” too. Basically, all case variations of “Apple” need to be changed to “apple”. Passing simple strings as an argument will no longer be practical or efficient in such cases.

This is where regular expressions come in—you could simply use the case-insensitive flag i and be done with it. With the flag in place, it doesn’t matter if the original string contained “Apples”, “APPles”, “ApPlEs”, or “Apples”. Every instance of the word will be replaced with “apples”.

Just like the case-insensitive flag, regular expressions offer a lot of other features which will be covered in this tutorial.

Using Regular Expressions in JavaScript

You have to use a slightly different syntax to indicate a regular expression inside different String methods. Unlike a simple string, which is enclosed in quotes, a regular expression consists of a pattern enclosed between slashes. Any flags that you use in a regular expression will be appended after the second slash.

Going back to the previous example, here is what the replace() method would look like with a regular expression and a simple string.

As you can see, the regular expression worked in both cases. We will now learn more about flags and special characters that make up the pattern inside a regular expression.

Backslash in Regular Expressions

You can turn normal characters into special characters by adding a backslash before them. Similarly, you can turn special characters into normal characters by adding a backslash before them.

For example, d is not a special character. However, d is used to match a digit character in a string. Similarly, D is not a special character either, but D is used to match non-digit characters in a string.

Digit characters include 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. When you use d inside a regular expression, it will match any of these nine characters. When you use D inside a regular expression, it will match all the non-digit characters.

The following example should make things clear.

You should note that only the first matched character is replaced in the third case. You can also use flags to replace all the matches. We will learn about such flags later.

Just like d and D, there are other special character sequences as well.

  1. You can use w to match any “word” character in a string. Here, word character refers to A-Z, a-z, 0-9, and _. So, basically, it will match all digits, all lowercase and uppercase alphabets, and the underscore.
  2. You can use W to match any non-word character in a string. It will match characters like %, $, #, ₹, etc.
  3. You can use s to match a single white space character, which includes space, tab, form feed, and line feed. Similarly, you can use S to match all other characters besides white space.
  4. You can also look for a specific white space character using f, n, r, t, and v, which stand for form feed, line feed, carriage return, horizontal tab, and vertical tab.

Sometimes, you will face situations where you need to replace a word with its substitute, but only if it is not part of a larger word. For example, consider the following sentence:

“A lot of pineapple images were posted on the app”.

In this case, we want to replace the word “app” with “board”. However, using a simple regular expression pattern will turn “apple” into “boardle”, and the final sentence would become:

“A lot of pineboardle images were posted on the app”.

In such cases, you can use another special character sequence: b. This checks for word boundaries. A word boundary is formed by use of any non-word characters like space, “$”, “%”, “#”, etc. Watch out, though—it also includes accented characters like “ü”.

Similarly, you can use B to match a non-word boundary. For example, you could use B to only match “app” when it is within another word, like “pineapple”.

Matching a Pattern “n” Number of Times

You can use ^ to tell JavaScript to only look at the beginning of the string for a match. Similarly, you can use $ to only look at the end of the string for a match.

You can use * to match the preceding expression 0 or more times. For example, /Ap*/ will match A, Ap, App, Appp, and so on.

In a similar manner, you can use + to match the preceding expression 1 or more times. For example, /Ap+/ will match Ap, App, Appp, and so on. The expression will not match the single A this time.

Sometimes, you only want to match a specific number of occurrences of a given pattern. In such cases, you should use the {n} character sequence, where n is a number. For instance, /Ap{2}/ will match App but not Ap. It will also match the first two ‘p’s in Appp and leave the third one untouched.

You can use {n,} to match at least ‘n’ occurrences of a given expression. This means that /Ap{2,}/ will match App but not Ap. It will also match all the ‘p’s in Apppp and replace them with your replacement string.

You can also use {n,m} to specify a minimum and maximum number and limit the number of times the given expression should be matched. For example, /Ap{2,4}/ will match App, Appp, and Apppp. It will also match the first four ‘p’s in Apppppp and leave the rest of them untouched.

Using Parentheses to Remember Matches

So far, we have only replaced patterns with a constant string. For example, in the previous section, the replacement we used was always “Add”. Sometimes, you will have to look for a pattern match inside the given string and then replace it with a part of the pattern.

Let’s say you have to find a word with five or more letters in a string and then add an “s” at the end of the word. In such cases, you will not be able to use a constant string value as a replacement as the final value depends on the matching pattern itself.

This was a simple example, but you can use the same technique to keep more than one matching pattern in memory. The number of sub-patterns in the full match will be determined by the number of parentheses used.

Inside the replacement string, the first sub-match will be identified using $1, the second sub-match will be identified using $2, and so on. Here is another example to further clarify the usage of parentheses.

Using Flags With Regular Expressions

As I mentioned in the introduction, one more important feature of regular expressions is the use of special flags to modify how a search is performed. The flags are optional, but you can use them to do things like making a search global or case-insensitive.

These are the four commonly used flags to change how JavaScript searches or replaces a string.

  • g: This flag will perform a global search instead of stopping after the first match.
  • i: This flag will perform a search without checking for an exact case match. For instance, Apple, aPPLe, and apPLE are all treated the same during case-insensitive searches.
  • m: This flag will perform a multi-line search.
  • y: This flag will look for a match in the index indicated by the lastIndex property.

Here are some examples of regular expressions used with flags:

Final Thoughts

The purpose of this tutorial was to introduce you to regular expressions in JavaScript and their importance. We began with the basics and then covered backslash and other special characters. We also learned how to check for a repeating pattern in a string and how to remember partial matches in a pattern in order to use them later.

Finally, we learned about commonly used flags which make regular expressions even more powerful. You can learn more about regular expressions in this article on MDN.

If there is anything that you would like me to clarify in this tutorial, feel free to let me know in the comments.


Source: Nettuts Web Development