Custom Error Message for PriceInCents – Vue3 and Vuelidate

Hey everyone,

This is a quick post to show how you can add a custom error message when using Vuelidate in Vue3. In my case I have a price field that should not be greater than $1000. The issue is that I store the amount in cents which results in the following error:

This is obviously a little ambiguous to the user who isn’t aware that everything is running in cents behind the scenes. In order to avoid the issue I used a helper in @vuelidate/validates:

// Import the following in your component
import {
  required,  
  maxValue,
  helpers, // Helpers provides access to the message customisation
} from "@vuelidate/validators";

...

// Add the following validation rule
priceInCents: {
          required,
          maxValue: helpers.withMessage("Price cannot be more than $1000.00" , maxValue(100000)),
        },

With the new rule in place the error is much more useful:

While it doesn’t seem to show up on Google too well this functionality is documented by Vuelidate on the following page: https://vuelidate-next.netlify.app/custom_validators.html#custom-error-messages

Missing .tsconfig when converting existing ReactJS project

Hi everyone,

I’ve finally decided to start learning typescript while working on a side project. The plan was to convert the existing project over using the following command:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

After restarting the web server I had expected to see a tsconfig.json file that would allow me to setup my preferred configuration. Unfortunately, mine was missing.

A bit of Googling revealed that the tsconfig file isn’t actually generated until you add a .ts or .tsx file to the project. In my case, I simply renamed an existing component and the configuration file was generated during the next startup. Note that you will also have to remove your jsconfig.json file (if you haven’t already).

Thanks to this blog for the detailed info: https://blog.bitsrc.io/why-and-how-use-typescript-in-your-react-app-60e8987be8de

Simple React-Leaflet Location Picker Setup

Hi everyone,

Just thought I’d share a very simple react-leaflet setup in case it’s able to help anyone.

screencast-localhost_3889-2019.08.24-14_01_41.gif

Add the css and javascript for leaflet to public > index.html:

  
https://unpkg.com/leaflet@1.5.1/dist/leaflet.js">https://unpkg.com/leaflet@1.5.1/dist/leaflet.js

Install react-leaflet via npm or yarn, also add the dependencies:

npm install react-leaflet # npm
npm install leaflet react react-dom # npm

yarn add react-leaflet # Yarn
yarn add leaflet react react-dom # Yarn

Create the map component:

import React, { useState } from 'react'
import { Map, TileLayer, Marker, Popup } from 'react-leaflet'


const MapSimple = () => {

    const [location, setLocation] = useState({
        lat: 51.505,
        lng: -0.09,
        zoom: 13,
    });
    const position = [location.lat, location.lng];
    
    const setMarkerPosition = e => {
        setLocation({ ...e.latlng, zoom: 19 });
        console.log(`My location is: ${JSON.stringify(e.latlng, null, 3)}`)
    };

    return (
        
            <TileLayer
                attribution='© OpenStreetMap contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            
                
                   A sample popup.
                
            
        
    )
}

export default MapSimple;

Check if Running Locally – AWS SAM & NodeJS

Hi everyone,

Just a quick post on how to check if code is being run locally with AWS SAM and NodeJS:

// 8+
isRunningLocally = () => {
    return process.env.AWS_SAM_LOCAL === 'true';
}

// 6+
function isRunningLocally() {
    return process.env.AWS_SAM_LOCAL === 'true';
}

Parsing Hash Args for Cognito Auth – Javascript

Hi everyone,

A quick post on a function for parsing hash args when using AWS Congito.

//jsfiddle.net/4eo7836j/embed/

Just in case the fiddle ever disappears:

const parseHashArgs = aURL => {

  aURL = aURL || window.location.href;

  var vars = {};
  var hashes = aURL.slice(aURL.indexOf('#') + 1).split('&');

  for (var i = 0; i  1) {
      vars[hash[0]] = hash[1];
    } else {
      vars[hash[0]] = null;
    }
  }

  return vars;
};

document.body.append(parseHashArgs("#id_token=testtokenval&token_type=bearer&expires_in=3600")["id_token"]);

Thanks to this link on Github: https://gist.github.com/miohtama/1570295/289d5a82e65663c9b515c88186a268c6dd1fddb7

NavLink ListItems not Applying activeClassName class when Clicked On – ReactJS React-Router MaterialUI

Hi everyone,

A bit of a hairy issue I ran into today that took a while to track down. I’m using React Router with Material UI to render a Drawer as a sidebar:

The issue was that some links were not applying the expected activeclass:


	
		
	
	<ListItemText primary={
		
			About
		
	} />

After trawling through react-router I eventually found a post on github that mentioned a similar issue: https://github.com/ReactTraining/react-router/issues/4638

The solution turned out to be wrapping all relevant components with withrouter.

Uncaught SyntaxError: Unexpected token < – ReactJS Build

Hi everyone,

A ReactJS issue I ran into after running npm run build:

Uncaught SyntaxError: Unexpected token <

This one took a while to track down but it essentially boils down to the built index.html file referencing paths relatively:

Issue: index.html was referencing
"</html".

Instead of:
"</html".

This meant that anytime a page was accessed directly it attempted to load the static files from the wrong directory. To fix it, I had to update the homepage node in package.json

Original:
...
"version": "0.1.0",
  "homepage": "./",
  "private": true,
...

Instead use:
"version": "0.1.0",
  "homepage": "/",
  "private": true,

Hopefully that’s able to help someone else out, took a while to track down!

Allow Number and String for PropTypes – ReactJS

Hi everyone,

A quick post on how to allow a string or number when defining PropTypes:

static propTypes = {
        numberField: PropTypes.number.isRequired,
        stringField: PropTypes.number.isRequired,
        mixedField: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired
    }

Thanks to this stackoverflow post for the info: https://stackoverflow.com/a/41808543/522859

VirtualDog Tutorial PluralSight

Hey everyone,

Just taking a quick look at Jasmine with Typescript and found a decent looking tutorial on PluralSight with a sample app called VirtualDog. Attempting to run the following command resulted in an error on Windows 10:

npm run bower-typings

> concurrently “bower install” “typings install”

[0] ‘bower’ is not recognized as an internal or external command,
[0] operable program or batch file.
[1] ‘typings’ is not recognized as an internal or external command,
[1] operable program or batch file.
[1] typings install exited with code 1
[0] bower install exited with code 1

npm ERR! Windows_NT 10.0.15063
npm ERR! argv “C:\Program Files\nodejs\node.exe” “C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js” “run” “bower-typings”
npm ERR! node v6.11.3
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! VitrualDog@0.0.1 bower-typings: `concurrently “bower install” “typings install” `
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the VitrualDog@0.0.1 bower-typings script ‘concurrently “bower install” “typings install” ‘.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the VitrualDog package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! concurrently “bower install” “typings install”
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs VitrualDog
npm ERR! Or if that isn’t available, you can get their info via:
npm ERR! npm owner ls VitrualDog
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! C:UsersChris-PCDesktopTesting Javascript with Jasmine and Typescriptvirtualdog-beginnpm-debug.log

In order to fix it, just run the following command:
npm install -g bower

Thanks to the following link: https://stackoverflow.com/a/37669968/522859