aboutusesTILblog

Today I learned about...
js

Back to all tags

js02.10.2024

colored console log

TIL that you can use console.log with color!

console.log(
  'This is %cMy stylish message',
  'color: yellow; font-style: italic; background-color: blue;padding: 2px',
)

Check it out

js26.08.2024

Storybook ArgeTypes

TIL that Storybook has a way to specify the behavior of argsArgeTypes. This is a great way to constrain the values that your component can accept and provides information about args that aren’t explicitly set in the story.

// Replace your-renderer with the renderer you are using (e.g., react, vue3, angular, etc.)
import type {Preview} from '@storybook/your-renderer'

const preview: Preview = {
  argTypes: {
    // 👇 All stories expect a label arg
    label: {
      control: 'text',
      description: 'Overwritten description',
    },
  },
}

export default preview

Check it out

js15.08.2024

Ecosystem Performance

TIL about e18e (Ecosystem Performance). It’s an initiative to connect folks and projects working on improving JS package performance.

Check it out

js09.08.2024

deepClone... nah, structuredClone

TIL that if we want to make a deepClone of an object in JS, there’s a built in method in most browsers: structuredClone!

The old one (which works but doesn’t account for things like Set and Map or even Date)

the-old-and-new-way
const originalObject = {
  name: "John",
  age: 30,
  date: new Date(),
  details: {
    hobbies: ["reading", "gaming"],
    address: {
      city: "New York",
      zip: "10001",
    },
  },
};

const clonedObjectOldWay = JSON.parse(JSON.stringify(originalObject));

// what do you think happened to the date? 😏
// hint... no longer a string!
console.log(clonedObjectOldWay);

console.log(originalObject.date instanceof Date); // true
console.log(clonedObjectOldWay.date instanceof Date); // false (Date is not preserved)

Shout out to Matt Pocock — the person behind Total Typescript — for the twitter thread that exposed me to this function!

Check it out

js21.06.2024

observables api

TIL, from Dom Farolino that he’s trying to make addEventListener extinct with the observables api!

// Filtering and mapping:
element
  .on('click')
  .filter(e => e.target.matches('.foo'))
  .map(e => ({x: e.clientX, y: e.clientY}))
  .subscribe({next: handleClickAtPoint})
js08.05.2024

patch-package

Got a node_module giving you a headache? Need to give it a band-aid? Thank your lucky stars for patch-package.

It’s a vital band-aid for the bleeding edge!

js30.04.2024

bundlephobia

If you ever want to know (sort of) the cost of adding a package to your node app, you can use bundlephobia!

js25.04.2024

Semver Calculator

During office hours with Kent, I learned about semver calculator!

It seems pretty dope and I’m going to use it in the future!

js10.04.2024

GROQ

I also learned that Sanity has their own query language for working with JSON. Might be worth looking into if you need to do some transformations and just move it into the query versus doing it in the code.

Check it out

js10.04.2024

Fluid frontvibe

TIL about a sick template for building a headless shopify theme with Sanity and Hydrogen.

Check it out

js14.03.2024

trigger.dev

Need to run background jobs? Not writing Ruby On Rails and therefore not using Sidekiq? Check out trigger.dev

I can probably use this somewhere in the future but TBD 🤔!

js11.10.2023

vercel serve

TIL about serve by vercel. It lets you serve your SPA/static files, incredibly easily! We may or may not be using it at work for some of our SPAs 😉.

Check it out!

js14.09.2023

every returns true for empty arrays

every on the JavaScript Array object is great since it checks to see if a given callback function is true for every value in the array… but there’s some caveats to it. Namely, every will return true for the empty array, and it does not take into consideration empty slots during its processing.

Refer to the following code to get an understanding of the caveats:

const isNumber = (v) => typeof v === 'number'

[].every(isNumber) // true
[1, ,2].every(isNumber) // true
[1, null, 2].every(isNumber) // false

js28.06.2023

shadcn

Check out Shadcn to learn more about re-usable components built using Radix UI and Tailwind CSS! It’s not a component library; you copy pasta the code you need into your project 😛!

js21.06.2023

Panda - a new spin on css-in-js

There’s a new kid on the block and this new kid is a game changer! Panda is a new css-in-js solution that works in the server-first framework era!

js26.04.2023

tailwind-merge

While working on my site, I realized that there was a nifty utility that handles merging my tailwind classes for me!

On NPM

js09.04.2023

Object.fromEntries

TIL that there’s a nifty methd on the Object type in JS: fromEntries. It’s the counterpart of entries method that exists on the Object.

Here’s an example for you:

let obj = {foo: 'bar', baz: 42}
const entries = Object.entries(obj)
console.log(entries)
// Expected output: [["foo", "bar"], ["baz", 42]]

obj = {}
console.log(obj)
// Expected output: {} 😆

obj = Object.fromEntries(entries)
console.log(obj)
// Expected output: Object { foo: "bar", baz: 42 }
js14.12.2022

Fusejs 🔥

As I was thinking about how I would migrate my search index for my site to remix, I came across an alternative to Lunrjs… and yes I know I can use Algolia but I personally think it’s overkill for what I want for my site.

Check it out

js07.12.2022

unifiedjs

So there’s this thing called unified that allows us to take things like Markdown, HTML, or plain text and turns it into structured data (AST) so that we can apply transformations on said data. Its rich plugin pipeline allows us to typically write one line of code to chain a feature into a process.

It’s more than this though as it is collective that spans multiple organizations and an ecosystem that includes:

  • remark
  • rehype
  • retext
  • redot

Check it out

js17.10.2022

DomMatrix

I was once asked about matrices in an interview. Still unsure how they work but we’ve got them in the browser specs 🤣.

Check it out

js11.10.2022

matchMedia

My mind was blown today when I learned that browsers now ship with a native way to easily check if the window matches a specific media query. 🤯

Essentially, you can pass in a media query into window.matchMedia and the returned object will tell you if the window matches you media query. It also ships with event listeners so you can handle resizing out of the box ❤️ .

Shout out to my main man Vepor for this piece of knowledge!

Check it out

js28.06.2021

History scrollRestoration

Turns out you can set up auto scroll restoration with browser APIs (yay!).

Check it out

js11.06.2021

RTK query and React Query

State management is hard but there’s a difference between state management in our apps versus managing our app’s server cache. Luckily, there are two libraries that we can use to help us with our server side state needs.

React query and RTK Query. We’re using React Query at work but RTK query looks cool too!

I’ll probably do a small POC this weekend to get a feel for the ergonomics.

js01.06.2021

Dates and stuff

Whenever you’re going to be talking about dates, keep these things in mind:

  1. Formatting (locale)
  2. Timezone (this dictates how much time to add based on UTC)
  3. UTC (know what this is)
js31.05.2021

Easier shell scripts

There’s a nifty little library to write shell scripts using node. Yay for less hassle!

Check it out

js27.05.2021

DateTimeFormat

Turns out that there’s a neat little time formatter that most browsers ship with that allows us to do locale specific time formatting. It’s inside of the Intl.

Intl.DateTimeFormat('en-US').format(Date.now())

Check it out…

js23.04.2021

document.activeElement

If you want to know what element on the page currently has focus, you can use document.activeElement to get access to the reference of the currently focused element.

I’m using it to handle the / key to force my website to move focus onto the search input (similar to what github does) and to not try to make the site refocus the search if is the currently active element.

js15.12.2020

toFixed vs toPrecision

toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length. Both will round! Both are functions that exist on the Number prototype!

js30.11.2020

volta

While working on a javascript monorepos course, I was exposed to Volta.

Volta eases the node development process by allowing developers to easily pin node versions to a project and will automatically switch the development machine to the right version when switching between contexts 😃.

js16.11.2020

npm i prefix

So you can actually run an npm install for a directory without having to actually change directories. Look: npm install --prefix /my/project/root

js12.11.2020

react-window

If you’re rendering over 50 rows in react-table and messing around with complicated filter logic, it’s wise to utilize something like react-window to get some performance gains as users are not going to be interacting with elements not in the viewport so we shouldn’t tax them for the rendering costs behind such frivolous elements.

js29.10.2020

toLocaleString

TIL that there is a method built into the Date object toLocaleString. It essentially allows us convert a date string to a locale specific string.

Check it out

js19.10.2020

window.open and max width/height

TIL that you can’t open a window in full screen with window.open

Check it out

js01.10.2020

Promise Extensions for JavaScript (prex)

While I was working on something at my day job, I learned about

prex.

It essentially allows us to cancel our promises (think axios or some other xhr).

token-example
return new Promise<void>((resolve, reject) => {
      const request = http.get(from);

      // abort the request if canceled.
      const registration = token.register(() => {
          request.abort();
          reject(new Error("Operation canceled."));
      });

      request.on("error", err => {
          registration.unregister();
          reject(err);
      });
}
js10.09.2020

Graceful Shutdown

Basically, avoid having to do any major logic from the SIGTERM signal or any other EXIT signals in node because they can often times be fired twice. It’s much better to run any clean up code that you want in the start of the process versus the end.

Also check out death on npm. It’s a handy helper library.

js01.09.2020

Xpaths and Shadow DOM

Turns out you can’t use Xpaths to access elements in a shadow dom.

Don’t use xpaths

js06.08.2020

console.info

TIL that Jest will buffer console.log statements but this is not true for console.info.

js05.08.2020

lodash fp

TIL that lodash-fp was merged into lodash but there are some discrepancies. For example, compose is flow and they both have curry.

js18.02.2020

Keyboard events, divs, and tabIndex

Vincent and I learned that if you’re attempting to add keyboard events to divs, you’ll want to supply a role and a tab-index if you’re wanting to react 😉.

js11.02.2020

Axios and Content-Type

During work today, my colleague Mo and I were having issues making DELETE requests to a micro service that he had created. In Postman and the standard XHR function that ships with Google Chrome, the delete requests were going through with no problem but when we tried to make a call via axios.delete(url/id), the server kept returning a 400 error.

The truly peculiar thing was that making a call in the following manner worked:

axios({
  method: 'DELETE',
  url: `url/${id}`,
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'Bearer SOME_TOKEN',
  },
})

However, this failed:

axios.delete(`url/${id}`, {
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'Bearer SOME_TOKEN',
  },
})

Long story short, TIL: axios.delete will drop the content-type header (which is the right behavior) so my buddy Mo had to change up his micro service endpoint to not expect a content type 😁!

js05.10.2020

package.json main vs module

TIL that the main attribute in package.json refers to the entry point for a commonjs node module and that the module attribute refers to the es module that can be used by bundlers such as wepback and rollup.

Check it out

js14.11.2019

Plop JS -- making your project structure consistent!

So here is a nice little thing I’m going to try and get people using at work, I hope! PLOP js!

It allows us to keep our project structure consistent by creating a CLI tool that will help automate the creation of files that should exist for various modules in our codebase. For example, if we are creating a React component, a structure that we’d like to enforce in order to keep our project neat and tidy is:

  1. componentName > file name
  2. componentName > index.js
  3. componentName > __tests__
js13.11.2019

Setting up your own private registry!

When it comes to managing npm packages for your organization, there’ a great little package called: Verdaccio. Verdaccio is a light-weight npm proxy registry. It allows us to host private Node.js packages and is compatible with all client package managers, such as Yarn and npm. There’s even a Docker image you can use to get you up and running!

js11.11.2019

Iterable and Iterators

Blog post about: Iterators, iterables, and generators! 🤓