Search After Stop Typing React Component

In this post I’m going to go through how to implement a search criteria component that only invokes the search in a calling component after the user has stopped typing.

So, we have the following search criteria component that invokes the search on a submit button at the moment:


… and this component is referenced like the following in a calling component:

At the moment, our submit button triggers the form’s submit which in tern calls handleSubmit() which then calls this.props.doSearch in our calling component to invoke the search (our calling component actually does the search).

Here’s what our component looks like at the moment:

We want to remove the submit button and just have the search invoke when the user stops typing.

So, let’s first remove the form and submit button from our render function:

Now let’s just invoke the search in handleCriteriaChange after we have set the criteria in the state:

So, our component invokes the search on every keystroke that the user does:

Not quite what we want!

We need to “debounce” the search. That’s where the debounce function in the excellent lodash library comes in.

So, let’s bring lodash and the TypeScript types into our project:

We now need to import just the debounce function into our component:

If we look at the docs, debounce just creates another function that delays calling another function. So, let’s create our “debounce” function leaving the console.log() so that we can check that doSearch is only being called when the user has stopped typing:


… and let’s call our new function from handleCriteriaChange:


… and let’s give this a try:

… which is just what we want!

Here’s the full code for our debouncing search criteria component:

Connect with me:RSSGitHubTwitterLinkedIn

Formatting dates and numbers in React

Formatting numbers and dates is a common requirement for lots of apps but how do we do this in react apps?

Let’s say we have a component in our app that shows a list of customers, looking like this:

… and here’s the current code for this component:

… with the following data:

You can see that we need to clean up the revenue and first sale data by formatting them.

Formatting numbers

We can use Intl.NumberFormat to format the revenue:


In the above example we are formatting to revenue using Great British locale, using the Great British currency style.

So, we now have this:

But what if we don’t want the decimals in the revenue? We just add the min and max fraction digits in the options:


Formatting dates

We could just use toLocaleDateString instead of toString:


… which gives us a nice short date:

However, we can use Intl.DateTimeFormat to gain more control on the formatting:


Here we are specifying a 2 digit day, a long month and a 4 digit year.

So, here’s our final CustomerSearchResults component code:


… and here’s what it looks like:

Much better!

Connect with me:RSSGitHubTwitterLinkedIn

Building a simple component in React.js v2

I’ve been using React again recently. It’s come along way in the last couple of years since I last blogged on building a simple search component. In this post I’ll build this component again using TypeScript with modern React constructs …

This is a link to the old code and below is what it looked like:

Getting started

To scaffold the app I used TypeScript-React-Starter.

The key steps are installing create-react-app …


… and then running it, referencing some TypeScript scripts …


You can then use the following command to start the app …

Basic component structure

The app is going to consist of the following components as we had in v1:

  • Criteria – responsible for the display and entry of the search criteria
  • ResultsList – responsible for the display of the search results
  • Search – this wraps the Criteria and ResultsList components and performs the actual search
  • App – the top level component for our app (essentially just wrapping the Search component)

Criteria component

Let’s start with our Criteria component …

This is a functional component with no state.

It takes the current criteria value in as a property which is then bound to the criteria input value.

It also takes in a delegate function in as a property which is bound to the form’s submit event via our handleSubmit() function.

Finally it takes in a delegate function in as a property which is bound to the criteria input change event via our handleCriteriaChange() function.

We are also using the arrow function notation to avoid the “this” scoping problem.

ResultsList component

Let’s move on to our ResultsList component …


This is also a functional component with no state that takes in the customers to display as a property value.

We make use of Array.prototype.map() to project the customers into a html list.

We also need to remember to include the key attribute so that React can properly manage changes to the html list.

The interface for Customer is:

Search component

Now on to our Search component …


This is our first component which has state which is why we are using a class component. Our state consists of:

  • allCustomers – a hardcoded array of all our customers
  • filteredCustomers – the current array of filtered customers
  • criteria – the current criteria

The state is intialised in the constructor with the filtered customers set to all the customers and the criteria set to an empty string.

The handleCriteriaChange() function catches changes to the criteria that are bubbled up from the Criteria component and sets the criteria bit of the state.

The doSearch() function catches the submit event from the Criteria component. It then does the appropriate filter on the array of customers using Array.prototype.filter(). Lastly it sets the filteredCustomers bit of the state.

The markup simply references the Criteria and ResultsList components, passing the appropriate properties.

App

Lastly, here’s our App functional component which simply wraps the Search component …

That’s it! The code certainly feels a lot cleaner than v1.

Connect with me:RSSGitHubTwitterLinkedIn

Integrating Validation in Angular 2 and ASP.NET Core

I’m building an Angular 2 app with an ASP.NET core web API behind it and need to add some validation. Obviously, I need to validate on the server in the web API, but I also want to do some client validation to make sure the user experience is good …

Server Validation

Here’s my model, which you can see is using attributes to define some required field validation:

Here’s our controller below.

If the required fields aren’t filled in (detected from the attribute validation) a HTTP 400 status code is returned with the validation errors in the response body.

We also do some more complex validation, checking if the email address is already in use. Again we return a 400 and the validation error if the email address exists in our database.

So, let’s test our API in Postman.

Test that required fields are validated:

Test that a valid person is saved:

Test that a person with an email address already in the database is validated:

Wiring up our Angular 2 app

Now, that we have our web API in place, let’s build our page to submit a new person.

At this point we’re not going to implement any clientside validation – we’re just going to handle the validation coming from the server.

Here’s our component markup:

  • Lines 1-7 will show the validation errors from the server
  • Lines 8-10 will show confirmation that the person has been saved into the database ok
  • Line 12 defines our form, telling angular that the form object will be called personForm and submit handler will be a function called onSubmit
  • Lines 14-46 define our field inputs for the person
  • Lines 48-52 defines our submit button

Here’s our component code:

  • Line 14 defines a variable called errors which will be an array of validation errors
  • ngOnInit on line 19 creates our form object with no client side validation defined at the moment
  • onSubmit posts the person object to our web API. You can see we catch validation errors on lines 47-55, pushing them to the errors array

If you run the app and hit the Submit button without filling in the inputs, you get something like:

Client Validation

Now, let’s implement the client validation in the angular app.

First, we need to change ngOnInit to include the validation rules:

Then, we need to change our markup for the field inputs to output the validation errors. Here’s the markup for the title input:

  • Line 1 adds the has-error CSS class if we have touched and not filled in the input
  • Lines 13-16 displays the error message beneath the input if we have touched and not filled in the input

So, cool, if the user doesn’t fill in any of the inputs, validation errors will be shown before the submit button is pressed:

However, what if we enter a duplicate email address:

As you can see, the validation error from the server is shown which is good, but ideally we want to highlight the email input and display the error beneath it. So, we need to integrate our validation errors from the server into Angular’s validation.

The solution is in the highlighted lines below. We know the field name from the server’s validation error dictionary. So, if the field is on our form, we flag to angular that there is an error using the control’s setErrors function.

In our example, we don’t have any validation that is not bound to a single field (cross field validation), but if we did, the validation errors would be shown at the top of the page.

Now, if we try to input a duplicate email, our user experience is much nicer:

If you want to learn more about making Angular and ASP.NET core work well together, I’d recommend reading ASP.NET Core and Angular 2

Connect with me:RSSGitHubTwitterLinkedIn

Getting the right version of TypeScript in a Visual Studio ASP.NET Core Project

I’m building an ASP.NET Core Angular 2 app. I think I’m using the latest version of TypeScript (2.1 at the moment) but I’m not sure …

If I open a command prompt and type:

it gives me:

So, great, my app must be using the 2.1?

Let’s check this by writing some 2.1 code:

Visual Studio complains straight away, putting a red squiggly line under the ...‘s. If you hover over the complaints, you get a tooltip saying “property assignment expected“.

Lets try running the app. It runs perfectly fine with mergedPerson correctly outputted to the console.

What’s going on? The visual studio compiler must be using a different version of TypeScript.

For classic ASP.NET projects, TypeScriptToolsVersion in csproj used to define the TypeScript version but that is no longer the case in ASP.NET core. In ASP.NET Core, this appears to be defined in a file called Microsoft.TypeScript.targets at C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\TypeScript:


So, this makes sense – Visual Studio appears to be using v1.8 (line 4).

Unfortunately, simply changing the 1.8 to 2.1 didn’t work for me.
I looked in my C:\Program Files (x86)\Microsoft SDKs\TypeScript directory. I only had a folder for 1.8.

Visual studio was obviously missing something, so, I downloaded and installed the latest version of TypeScript for Visual Studio.

Voila! The red squiggly lines disappeared in Visual Studio, my app still ran fine and the version references in C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\TypeScript\Microsoft.TypeScript.targets has been upgraded to 2.1.

Connect with me:RSSGitHubTwitterLinkedIn

Taking Stripe Payments with Angular 2 and ASP.NET Core

Stripe is a service that allows you to very easily take payments online. In this post, I’ll go through how to take a payment via stripe using an Angular 2 frontend and an ASP.NET Core backend.

Sign up to Stripe

Firstly, we need to sign up for a stripe account. You can signup for a free test account here

After you have signed up, we need the Secret and Publishable keys. You can get these from Your account > Account settings > API Keys

Frontend Page

Let’s build the frontend first, using an Angular 2 component.

We are going to use stripe checkout which is super easy to implement and protects us from any PCI headaches (as long as our site runs on HTTPS).

First, we need to add a reference to the standard stripe checkout JavaScript in our server side ASP.NET Core view (line 3). This adds the global variable StripeCheckout which we’ll reference in our angular component. Note that we can not add this script into our angular component template because angular will remove it.

Now let’s add our angular payment component …

Here’s the simple markup (referencing bootstrap classes) which allows a user to buy 3 products, a T-shirt, some trainers or some jeans. Each button will invoke a function in our component code to take the payment via stripe. We show whether the payment has been successful or not in the last div in the markup, referencing a property called takePaymentResult.

Our component code is below …

Our 3 button handlers at are the bottom of the code and simply call into openCheckout() passing the product name, amount (in pence) and a callback to get invoked when we receive a token from stripe.

openCheckout() references the global variable StripeCheckout from checkout.js. Firstly we configure StripeCheckout, passing our publishable key and then we open the stripe payment form passing in our product and amount for the transaction.

After the user enters their credit card details and presses the Pay button, these details will be sent to stripe to initiate the payment. Stripe will then return a token and our callback (takePayment()) will be invoked.

takePayment() will call our ASP.NET Core API (/api/stripepayment) using angular’s http service. This is where the stripe payment will be processed – we’ll implement this in a minute.

The status from the /api/stripepayment API response is put in takePaymentResult which will be presented in the UI by angular.

Web API

OK, on to our web API that processes the stripe payment …

First, we need to bring in stripe.net via nuget – it makes processing the payment very simple.

Below is the full API controller and the API request model, StripePaymentRequest

First we tell stripe our secret key (line 7). We then setup the stripe charge object, setting the token, amount and description (to the product name). We also set our payment reference in the MetaData dictionary so that we tie the payment in our app to the payment in stripe.

The charge is then made and the result (which includes whether the payment has been successful) is passed back down in the response.

Test it!

You can test different scenarios using stripe’s test credit card numbers here.

Connect with me:RSSGitHubTwitterLinkedIn

8 Reasons to use TypeScript

I’ve been using TypeScript again whilst using Angular 2. I dismissed TypeScript a few years ago because the tooling surrounding it was a bit too painful and I didn’t think it would gain traction. Things have improved a lot. Here’s why I think it is worth considering using TypeScript – particularly when writing decent sized web apps …

1. Readability

The TypeScript syntax is really nice – I find it easier to read than the equivalent JavaScript. This can have a significant impact on the maintenance cost with large codebases with large teams. Here’s some sample TypeScript on the left and the equivalent JavaScript on the right:

You can see that the TypeScript is much cleaner – no IFFE to mimic a class or “prototype” references when defining functions, …

2. ES6 in older browsers

TypeScript lets you use ES6 features today in older browsers because TypeScript can compile to ES5. Features like classes in the above example, arrow functions in the example allow you to write cleaner code …

3. IntelliSense

IntelliSense allows you to understand APIs quicker. Again this can improve productivity in large codebases.

4. Familiar Object Oriented style

The TypeScript syntax is very similar C# and Java. So, if you have a lot of experience in these languages, you will be right at home with TypeScript.

5. Catch errors quicker

TypeScript can catch errors as you write your code. A common mistake I make with JavaScript is typing out the wrong property or function name when consuming an API. Without TypeScript, these errors are caught when you run the code or when you write a unit test. With TypeScript, these errors are caught as you type the incorrect code. Again, this improves productivity.

6. Not all or nothing

The migration to TypeScript can be gradual – you don’t have to migrate every line of code from JavaScript to TypeScript before releasing. You can migrate the short, simple files that are referenced a lot first, to start gaining a good level of benefit. You don’t have to migrate all areas of code to TypeScript as well – there are cases when strong typing adds a lot of friction.

7. Traction

Looking at Google Trends, TypeScript has continued to gain traction in the last couple of years since release. Angular 2’s dependency on TypeScript will mean that traction will continue to grow – Angular is hugely popular.

8. Mature

TypeScript was released to the general public towards the end of 2012 after 2 years of internal development at Microsoft.
So, there’s been lots of development following feedback in the last couple of years. The tooling surrounding TypeScript is now much better and WebStorm and Visual Studio Code now give excellent experiences now when writing TypeScript code.

Connect with me:RSSGitHubTwitterLinkedIn

Building a simple component in React.js – Part 1 – Intro and Basic UI

In the next 3 posts, we’re going to build search and results components using React.js. The components will allow you to search for a company name and the matching names will be displayed beneath the search box.

The components will look like below. There will be 3 components:

  1. Criteria. The search textbox and “go” button
  2. Results. The list of results
  3. Search. The overall component – the parent of Criteria and Results

Consuming page

The html of the consuming page is listed below.

  • Line 10 is a placeholder for where the components will be injected
  • Line 12 is a reference to React.js
  • Line 13 is a reference to the React library that will transform the JSX in our components into valid HTML / JS
  • Line 15 is a placeholder for where we are going to write our React components

Creating our 3 basic components

You create a component in React.js by calling React.createClass(). The key function within a React component, that you must implement, is render() which should return the JSX for the component – JSX is a lot like HTML.

In the code below, we create our 3 component classes, returning the basic JSX we need.

  • Line 24 defines the outer component referencing the sub components, Criteria and Results
  • Line 2 defines the Criteria component
  • Line 13 defines the Results component with some hardcoded results at this point
  • Line 35 is where we tell React to inject the outer component, Search, into the DOM node with id “app”

In subsequent parts we will build on these component implementations …

Connect with me:RSSGitHubTwitterLinkedIn