Categories
Vuetify

Vuetify — Autocomplete and Combobox

Vuetify is a popular UI framework for Vue apps.

In this article, we’ll look at how to work with the Vuetify framework.

Async Autocomplete

The v-autocomplete components work with async data sources.

For example, we can write:

<template>
  <v-container>
    <v-row>
      <v-col col="12">
        <v-toolbar dark color="teal">
          <v-toolbar-title>State</v-toolbar-title>
          <v-autocomplete
            v-model="select"
            :loading="loading"
            :items="items"
            :search-input.sync="search"
            cache-items
            class="mx-4"
            flat
            hide-no-data
            hide-details
            label="State"
            solo-inverted
          ></v-autocomplete>
          <v-btn icon>
            <v-icon>mdi-dots-vertical</v-icon>
          </v-btn>
        </v-toolbar>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      loading: false,
      items: [],
      search: null,
      select: null,
      states: [
        "Alabama",
        "Alaska",
        "American Samoa",
        "Arizona",
        "Arkansas"
      ],
    };
  },
  watch: {
    search(val) {
      val && val !== this.select && this.querySelections(val);
    },
  },
  methods: {
    querySelections(v) {
      this.loading = true;
      setTimeout(() => {
        this.items = this.states.filter((e) => {
          return (e || "").toLowerCase().indexOf((v || "").toLowerCase()) > -1;
        });
        this.loading = false;
      }, 500);
    },
  },
};
</script>

We have the select state which is the model for the autocomplete.

And we have a watcher search to make the query when the search state changes.

In the querySelections method calls filter to filter the items.

Combobox

The v-combobox component is a v-autocomplete that lets us enter values that don’t exist with the provided items.

The created items will be returned as strings.

For example, we can write:

<template>
  <v-container>
    <v-row>
      <v-col col="12">
        <v-combobox
          v-model="select"
          :items="items"
          label="Select activity"
          multiple
        ></v-combobox>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      select: ["Vue"],
      items: ["Programming", "Vue", "Vuetify"],
    };
  },
};
</script>

to add a v-combobox component to create the dropdown.

items populate the items with the items array.

We have the multiple prop to enable multiple selections.

label has the label for dropdown.

v-model sets the state from the selected item.

Now we see a dropdown with the items we can select.

Also, we can populate the data slot with our own choice.

For instance, we can write:

<template>
  <v-container>
    <v-row>
      <v-col col="12">
        <v-combobox v-model="select" :items="items" label="Select activity" multiple chips>
          <template v-slot:selection="data">
            <v-chip
              :key="JSON.stringify(data.item)"
              v-bind="data.attrs"
              :input-value="data.selected"
              :disabled="data.disabled"
              @click:close="data.parent.selectItem(data.item)"
            >
              <v-avatar
                class="accent white--text"
                left
                v-text="data.item.slice(0, 1).toUpperCase()"
              ></v-avatar>
              {{ data.item }}
            </v-chip>
          </template>
        </v-combobox>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      select: ["Vue"],
      items: ["Programming", "Vue", "Vuetify"],
    };
  },
};
</script>

We have populate the selection slot with the v-chip component.

Dense

We can use the dense prop to reduce the combo box height and max height of the list items:

<template>
  <v-container>
    <v-row>
      <v-col col="12">
        <v-combobox v-model="select" :items="items" label="Select activity" multiple dense></v-combobox>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      select: ["Vue"],
      items: ["Programming", "Vue", "Vuetify"],
    };
  },
};
</script>

Conclusion

We can get async data with autocomplete.

Also, we can add a combobox to add a dropdown where we can add items.

Categories
JavaScript Tips

Useful JavaScript Tips — Sleep and Math

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Pause Execution of a Function

We can pause execution of a function by creating our own sleep function.

For instance, we can write:

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms))
}

We return a promise with the setTimeour function. The callback is the resolve function.

ms is the amount of pause execution in ms .

Then we can use it by writing:

const foo = async () => {
  await sleep(2000);
  // do more stuff
}

We called sleep with 2000 so the function will pause for 2 seconds before running the code below the sleep call.

It can be used with a loop:

const loop = async () => {
  for (const item of arr) {
    await sleep(2000);
    console.log(item);
  }
}

for-of loops can be used with promises.

So sleep will pause the loop body for 2 seconds.

Generate Random and Unique Strings

We can use the randomstring package to generate random strings.

For instance,e we can wrote:

const randomstring = require('randomstring');
`randomstring.generate(20);`

to generate a string of length 20.

To generate multiple unique strings, we can put all the items in a set.

For instance, we can write:

`const randomstring = require('randomstring');
`const strings = new Set()

while (strings.size < 50) {
  strings.add(randomstring.generate(20));
}

Then we generate unique strings until the set has 50 strings.

Then we can retrieve the strings with the values method.

For instance, we can write:

for (const value of strings.values()) {
  console.log(value);
}

JavaScript Math Object

JavaScript Math object has many properties and methods to make doing math easier.

Math.abs()

The Math.abs method returns the absolute value of a number.

We can write:

Math.abs(-10)

and get 10.

Math.acos()

Returns the arccosine of the argument.

For instance, we can write:

Math.acos(0.3)

and we get 1.2661036727794992.

Math.asin()

Returns the arcsine of the argument.

For instance, we can write:

Math.asin(0.5)

and we get 0.5235987755982989.

Math.atan()

Returns the rectangle of the argument.

For example, we can write:

Math.atan(20)

and we get 1.5208379310729538.

Math.atan2()

Returns the arctangent of the quotient of its arguments.

For instance, we can write:

Math.atan2(3, 2)

and get 0.982793723247329.

Math.ceil()

Rounds a number up to the nearest integer.

For instance, we can write:

Math.ceil(1.99999)

and get 2.

Math.cos()

Returns the cosine of the angle expressed in radians.

For example, we can write:

Math.cos(0)

and get 1.

Math.exp()

Returns the value of e multiplied per exponent that’s passed as the argument.

For example, we can write:

Math.exp(2)

and get 7.38905609893065.

Math.floor()

Rounds the number down to the nearest integer.

For instance, we can write:

Math.floor(1.99999)

and get 1.

Math.log()

Gets the natural logarithm of a number.

For instance, we can write:

Math.log(Math.E)

and get 1.

Math.max()

Gets the maximum number in the set of numbers passed as arguments.

For instance, we can write:

Math.max(1, 2, 3)

and get 3.

Math.min()

Gets the minimum number in the set of numbers passed as arguments.

For example, we can write:

Math.max(1, 2, 3)

and get 1.

Math.pow()

Raised the first argument to the second argument.

For instance, we can write:

Math.pow(2, 3)

and get 8.

Math.random()

Returns a pseudorandom number between 0 and 1.

For instance, we can write:

Math.random()

and get 0.08500663407619236.

Math.round()

Returns the nearest integer.

For instance, we can write:

Math.round(1.3)

and get 1.

Math.sin()

Gets the sine of the angle expressed in radians.

For example, we can write:

Math.sin(0)

and get 0.

Math.sqrt()

Gets the square root of the argument.

For instance, we can write:

Math.sqrt(9)

and get 3.

Math.tan()

Gets the angle of an angle in radians.

For instance, we can write:

Math.tan(Math.PI * 2)

and we get -2.4492935982947064e-16.

Arithmetic Operators

JavaScript has the usual arithmetic operators.

They’re addition, subtraction, multiplication, division, remainder, and exponentiation.

Then we can write:

const three = 1 + 2;

for addition.

But we’ve to make sure that both operands are numbers. Otherwise, it’s used as concatenation.

Subtraction is written as:

const three = 5 - 2;

Division can be written as:

const result = 20 / 10;

If we divide by zero, we get Infinity or -Infinity .

Multiplication can be done by writing:

1 * 2

We can exponentiate by writing:

2 ** 3

and get 8.

We can get the remainder of division by writing:

const result = 20 % 6

and get 2.

Conclusion

There are many operations and math methods we can use.

Also, we can pause execution of functions by using setTimeout .

Categories
JavaScript Tips

Useful JavaScript Tips — Query Strings Rounding, and URLs

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Getting Query String Values

JavaScript’s standard library has the URLSearchParams constructor that can be used to extract the query parameters and let us search for them.

For instance, we can write:

const urlParams = new URLSearchParams(window.location.search);
const val  = urlParams.get('key');

window.location.search returns the query string portion of the URL.

The get method gets the value by the key of the query parameter.

Round a Number to at Most 2 Decimal Places

We can use Math.round to let us round to 2 decimal places.

For instance, we can write:

Math.round(num * 100) / 100

We multiplied num by 100, round it, and then divide by 100 to return a number that has at most 2 decimal places.

If there are decimal digits that are less than the hundredth digit, then we add Number.EPSILON to before we multiply by 100.

So we write:

Math.round((num + Number.EPSILON) * 100) / 100

Also, we can use parseFloat and toFixed to format a number into a string of the number with 2 decimal places.

We can write:

parseFloat("575.393").toFixed(2);

Convert a String to Boolean

We can convert the string 'true' and 'false' to their corresponding boolean value by writing:

val === 'true'

Assuming that val can be set to 'true' or 'false' , we can just compare against 'true' to do that.

Storing Objects in Local Storage

To store an object in local storage, we’ve to convert it to a string first.

For instance, we can write:

const obj = { 'foo': 1, 'bar': 2, 'baz': 3 };
localStorage.setItem('data', JSON.stringify(obj));

We called JSON.stringify before calling setItem to store the stringified object with the key data in local storage.

JSON.stringify won’t keep undefined , functions, Infinity, and regex, so we’ve to be careful about that.

Merge 2 or More Objects

We can use the spread operator or Object.assign to merge the properties of 2 or more objects together.

For instance, we can write:

const merged = {...obj1, ...obj2, ...obj3};

or:

const merged = Object.assign({}, obj1, obj2, obj3, etc);

Both pieces of code populate the properties of obj1 , obj2 , and obj3 into an empty object.

Detect a Click Outside an Element

We can call stopPropagation to prevent the click event from the element that we’re checking the click from the outside of.

So we can write:

window.addEventListener('click', () => {
  // do something when clicked outside
});

document.querySelector('#menucontainer').click((event) => {
  event.stopPropagation();
});

The window ‘s click event handler lets us run code when the user clicks outside.

Refresh a Page

There are many ways to refresh a page with JavaScript,

We can do:

  • location.reload();
  • history.go(0)
  • location.href = location.href
  • location.href = location.pathname
  • location.replace(location.pathname)
  • location.reload(false)

location.pathname is the relative URL.

history.go also refreshes by reloading the same page.

Pretty Print JSON

We can pretty-print JSON with the JSON.stringify method.

For example, we can write:

const str = JSON.stringify(obj, null, 2);

The 2 indicates that we indent by 2 spaces.

Passing Command Lines Arguments to a Node.js Program

Node programs have access to the process.argv property to get all the command line arguments of a program.

For instance, we can write:

for (const a of process.argv){
  console.log(a)
}

The first argument is always 'node' . The 2nd is always the path of the file we run.

The rest are the other command-line arguments.

Check for Decimal Numbers

We can check for decimal numbers by using the isNaN function and the isFinite function.

To do the check, we write:

!isNaN(parseFloat(n)) && isFinite(n);

parseFloat parses the string into a floating-point number.

isNaN checks whether the returned value is NaN or not.

isFinite checks whether the number or numeric string represents a finite number.

Modify the URL Without Reloading the Page

The URL can be modified without reloading the page with JavaScript.

The window.history.pushState lets us add a new URL to the browsing history.

We can write:

window.history.pushState('foo', 'title', '/foo.html');

The first argument is the state object.

We can take get the value of the argument with popstate .

'title' is the title, which is ignored in most browsers.

'/foo.html' is the URL to write to the browsing history.

Conclusion

The URLSearchParams constructor lets us parse query strings into a useful object that we can look up.

We can use Math.round to round a number to 2 decimal places.

Also, we can change the URL and add it to the browsing history without reloading the page.

Categories
JavaScript Tips

JavaScript Tips— Textbox Values, Timezones, and Loops

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Check if a Textbox has Changed

We can check if a textbox has changed by listening to the input event.

For instance, we can write:

$('#text-box').on('input', () => {
  // ...
});

We call on to listen to the input event.

Then we run the code in the callback to do what we want.

Detect a Touch Screen Device Using JavaScript

We can use the Modernizr library to detect whether a device is a touch screen device or not.

It provides us with the touch and no-touch classes which are added to the html element.

Therefore, we can use that to do whatever we want depending on whether the device is touch screen or not.

The Correct Way to Modify State Arrays in React

There is a correct way to modify state arrays in React.

If we’re using class components, we use setState by passing in a callback that takes the previous value.

Then we return a new value based on that.

For instance, we can write:

this.setState(prevState => ({
  arr: [...prevState.arr, 'foo']
}))

We added the 'foo' string as the last element of the arr state.

If we’re using hooks, we do the same thing but we pass the callback into the state change function.

For instance, we write:

`setArr(`arr => [...arr, 'foo']`)`

assuming setArr is the state change function returned by useState .

Check if a Number is NaN

To check if a number is NaN , we need to use the isNaN function.

For instance, we can write:

isNaN('foo')

It’ll check by converting the string to a number and then do the check.

So it’ll return true since it’ll be converted to NaN .

Finding the Max Value of a Property in an Array of Objects

We can use the Math.max and the array map methods to find the max value of a property in an array of objects.

For instance, we can write:

Math.max(...array.map(o => o.y))

We get the max value of the y property of the entries by call map to return an array of numbers with the values.

Then we use the spread operator to spread the array entries into the Math.max method as arguments.

How to Toggle a Boolean

We can toggle a boolean by using the ! operator.

We just write:

bool = !bool;

to change bool to the value opposite of the current one.

Create a Date with a Set Timezone Without Using a String Representation

We can create a Date object with a set timezone without using a string by using the setUTCHours method to set the UTC hour of a Date instance.

For instance, we can write:

new Date().setUTCHours(2)

Then we get the timestamp of the date with the hour set to the given UTC hour.

We can also set the minutes, seconds, and milliseconds values.

Also, we can write:

const date = `new Date(Date.UTC(year, month, day, hour, minute, second))`

Date.UTC returns a timestamp with the UTC date set with the given year, month, day, hour, minute, and seconds.

When we pass that into the Date constructor, we get the date with the same value.

Looping Through Key-Value Pairs

To loop through key-value pairs, we can use Object.entries with the for-of loop.

For instance, we can write:

for (const [key, value] of Object.entries(obj)) {
  console.log(key, value);
}

to do that.

obj is an object.

Scroll Automatically to the Bottom of the Page

To scroll automatically to the bottom of the page, we can use the window.scrollTo method.

For example, we can write:

window.scrollTo(0, document.body.scrollHeight);

We scroll to the x and y coordinates given in the argument.

document.body.scrollHeight is the bottom of the page.

Conclusion

window.scrollTo lets us scroll to anywhere on our page.

The right way to modify an array state in React is to pass in a callback and return a new array derived from the old one.

We can watch the input event of a text area to watch the value as we type.

We can use Math.max to find the max value of an array of numbers.

Categories
JavaScript Tips

JavaScript Tips — Sets to Arrays, Console Log, Size of Text, and More

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Convert a Set to an Array

There are a few ways to convert a set to an array.

One way is to use the Array.from method.

For instance, we can write:

const array = Array.from(set);

We can also use the spread operator to do the same thing:

const array = [...set];

Call a Method from a Child Component from a Parent

We can call a method from a child component in the parent by assigning a ref to the child component.

Then we can access the child with the current property.

For instance, we can write:

const { forwardRef, useRef, useImperativeHandle } = React;

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    getAlert() {
      console.log("alert from child");
    }
  }));
  return <h1>hello</h1>;
});

const Parent = () => {
  const childRef = useRef();
  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click</button>
    </div>
  );
};

We use the forwardRef function to pass the ref to the child component.

useImperativeHandle lets us expose a selected method of the child to the parent.

Now we assign the ref to the Child and then we can call the getAlert method from the Parent via the current property.

How to Fix Error: listen EADDRINUSE Error

EADDRINUSE means that the port number is already in use.

This means that we have to listen to a different port in whatever app we’re using.

Or we can end the program that’s using the port we want to use.

For instance, if we change the port of an HTTP server, we can write:

const http = require('http');

const server = http.createServer((req, res) => {
  res.end('test');
});

server.on('listening', () => {
  console.log('ok, server is running');
});

server.listen(80);

The last line is listening to port 80.

We can change that to something else.

To terminate a program, we can write:

killall -9 node

Print Debug Messages in the Google Chrome JavaScript Console

We can run JavaScript in the browser address bar with the javascript: prefix.

For instance, we can type in:

javascript: console.log('foo');

to log 'foo' in the console.

Other console methods include console.error to log things as errors.

console.info logs informational messages.

console.warn logs warnings.

We can format strings with some tags.

For instance, we can write:

console.log("this is %o, event is %o, host is %s", this, e, location.host);

%o means we interpolate an object, and %s means string.

Firefox has the console.trace(); method to log stack traces.

Better Way of Writing v = (v === 0 ? 1 : 0)

We can rewrite v = (v === 0 ? 1 : 0) to:

v = (v ? 0 : 1);

since 0 is falsy.

If v is 0 or another falsy value, then we assign 1 to it. Otherwise, we assign 0.

Return Value from an Asynchronous Callback Function

There’s no way to return a value from an async callback function.

This is because we get the value in an indeterminate amount of time.

Instead, we just use the value inside the function.

So if we have:

asyncCode({ address }, (results, status) => {
  fn(results[0].geometry.location);
});

Then we just use results and status within the function.

Calculate Text Width

We can calculate the text width by putting our text in a div.

Then we can use the clientWidth and clientHeight properties to get the width and height respectively.

For instance, we can write:

const fontSize = 12;
const text= document.getElementById("text");
text.style.fontSize = fontSize;
const height = `${text.clientHeight}px`;
const width = `${text.clientWidth}px`;

With just get the text, change the font size to what we want, and get those properties.

Check Whether Variable is a Number or a String

To check whether a variable is a number or a string, we can use the typeof operator.

For instance, we can write:

typeof "hello"

and get 'string'

And if we write:

typeof 123

we get 'number'.

Conclusion

There are a few ways to convert a set to an array.

We can call a method from a React child component from a parent component by using forward refs.

There are many ways to log items in JavaScript.

There’s no way to return a value from an async callback function.