Javascript 63

How to use React Query useQuery with debounce

Issue #979

When dealing with user input, such as in an autocomplete component, it’s common to implement debouncing to reduce the number of API calls and improve the user experience.

React Query’s useQuery hook makes it easy to manage the …

How to serve a local development environment over https using pnpm and webpack

Issue #976

When developing locally, especially when interacting with third-party services that have CORS restrictions, serving your development environment over a custom domain with HTTPS can be crucial. Let’s walk through the steps to achieve this …

How to use memory in lowdb

Issue #974

In lowdb 7, we can use MemorySync https://github.com/typicode/lowdb/blob/main/src/examples/in-memory.ts

import { LowSync, MemorySync, SyncAdapter } from '../index.js'
import { JSONFileSync } from '../node.js'

declare …

How to include custom error payload in hapi Boom

Issue #969

Hapi.js, commonly referred to as Hapi, is an open-source, back-end web application framework for building and deploying web applications and APIs in Node.js

In Hapi.js, you can use the Boom module to create and return error responses in a …

How to use useCallback in React

Issue #966

The use of useCallback and useMemo in React hooks is an adaptation to address certain limitations inherent in the functional programming style adopted by React. In JavaScript, every entity, whether it’s a function, variable, or any …

How to extend class in Javascript

Issue #965

In JavaScript, classes are a template for creating objects. They encapsulate data with code to work on that data. ES6 introduced a class syntax to the JavaScript language to create classes in a way that’s similar to other …

How to use export all and export default in Javascript

Issue #964

In JavaScript, particularly in modules used in frameworks like React, export statements are used to expose code—such as functions, classes, or constants—from one module so that they can be imported and reused in other modules.

export *

The …

How to debounce text input in React

Issue #953

Use debounce from lodash and useCallback to memoize debounce function

import React, { useCallback } from "react"
import debounce from "lodash/debounce"

const SearchField = (props: Props) => {
    const callback = …

How to remove duplicates in Javascript array while keeping latest occurrence?

Issue #952

Use ES6 Map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

type Deal = {
    name: string,
    link: …

How to dynamically build tailwind class names

Issue #950

Inspired by shadcn

Combine

  • tailwind-merge: Utility function to efficiently merge Tailwind CSS classes in JS without style conflicts.
  • clsx: constructing className strings conditionally.
import { clsx, type ClassValue } from "clsx" …

How to handle route case sensitivity in Nextjs

Issue #933

By default, Nextjs route is case sensitive, so localhost:3000/About and localhost:3000/about are different routes.

To make uppercase routes become lowercase routes, we can add a middleware.tsx file to the src so it is same level as pages …

How to render markdown view with React

Issue #914

Use react-markdown to parse markdown content, react-syntax-highlighter to highlight code, and rehype-raw to parse raw html

import ReactMarkdown from "react-markdown"
import { Prism as SyntaxHighlighter } from …

How to use relative file module with Create React app

Issue #751

Declare data/package.json to make it into node module

{
    "name": "data",
    "version": "0.1.0",
    "private": true,
    "homepage": ".",
    "main": "main.js"
} …

How to format ISO date string in Javascript

Issue #705

Supposed we have date in format ISO8601 and we want to get rid of T and millisecond and timezone Z

const date = new Date()
date.toDateString() // "Sat Dec 05 2020"
date.toString() // "Sat Dec 05 2020 06:58:19 GMT+0100 (Central …

How to make simple overlay container in React

Issue #699

Use term ZStack like in SwiftUI, we declare container as relative position. For now it uses only 2 items from props.children but can be tweaked to support mutiple

class App extends React.Component {
    render() {
        return ( …

How to use useEffect in React hook

Issue #669

Specify params as array [year, id], not object {year, id}

const { year, id } = props
useEffect(() => {
        const loadData = async () => {
            try {
                
            } catch (error) {
                console. …

How to format date in certain timezone with momentjs

Issue #664

Use moment-timezone https://momentjs.com/timezone/docs/

npm install moment-timezone

// public/index.html
<script src="moment.js"></script>
<script src="moment-timezone-with-data.js"></script>

Need …

How to handle evens in put with React

Issue #661

Use Bulma css

<input
    class="input is-rounded"
    type="text"
    placeholder="Say something"
    value={value}
    onChange={(e) => { onValueChange(e.target.value) }}
    onKeyDown={(e) => {
        if …

How to handle events for input with React

Issue #661

Use Bulma css

<input
    class="input is-rounded"
    type="text"
    placeholder="Say something"
    value={value}
    onChange={(e) => { onValueChange(e.target.value) }}
    onKeyDown={(e) => {
        if …

How to auto scroll to top in react router 5

Issue #659

Use useLocation https://reacttraining.com/react-router/web/guides/scroll-restoration

import React, { useEffect } from 'react';
import {
    BrowserRouter as Router,
    Switch,
    Route,
    Link,
    useLocation,
    withRouter
} …

How to use dynamic route in react router 5

Issue #658

Declare routes, use exact to match exact path as finding route is from top to bottom. For dynamic route, I find that we need to use render and pass the props manually.

Declare Router as the rooter with Header, Content and Footer. Inside …

How to use folder as local npm package

Issue #657

Add library folder src/library

src
    library
        res.js
    screens
        Home
            index.js
package.json

Declare package.json in library folder

{
    "name": "library",
    "version": "0.0.1" …

How to scroll to element in React

Issue #648

In a similar fashion to plain old javascript, note that href needs to have valid hash tag, like #features

<a
    href='#features'
    onClick={() => {
        const options = {
            behavior: 'smooth'
        } …

How to make simple filter menu in css

Issue #643

Use material icons

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
div#filter-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: …

How to add independent page in hexo

Issue #641

Create a new page

hexo new page mydemo

Remove index.md and create index.html, you can reference external css and js in this index.html. Hexo has hexo new page mydemo --slug but it does not support page hierarchy

Specify no layout so it is …

How to use async function as parameter in TypeScript

Issue #640

async function useCache(
    collectionName: string, 
    key: string, 
    response: functions.Response<any>, 
    fetch: () => Promise<any>
): Promise<any> {
    const existing = await db.collection(collectionName). …

How to get ISO string from date in Javascript

Issue #552

type Components = {
  day: number,
  month: number,
  year: number
}

export default class DateFormatter {
  // 2018-11-11T00:00:00
  static ISOStringWithoutTimeZone = (date: Date): string => {
    const components = DateFormatter. …

How to apply translations to Localizable.strings

Issue #492

Suppose we have a base Localizable.strings

"open" = "Open";
"closed" = "Closed";

After sending that file for translations, we get translated versions.

"open" = "Åpen";
"closed" = …

How to use react-native link and CocoaPods

Issue #476

React Native comes with a default React library, and most CocoaPods libraries for React Native has React as a dependency pod, which causes the conflict

How to notarize electron app

Issue #430

Use electron builder

npm install electron-builder@latest --save-dev

package.json

{
  "name": …

How to use custom domain for GitHub pages

Issue #423

In DNS settings

Add 4 A records

A @ 185.199.110.153
A @	185.199.111.153
A @	185.199.108.153
A @	185.199.109.153

and 1 CNAME record

CNAME www learntalks.github.io

In GitHub

  • Select custom domain and type learntalks.com

In source …

How to replace all occurrences of a string in Javascript

Issue #420

const normalized = string
   .replace(/\//g, '')
   .replace(/\"/g, '')
   .replace(/\(/g, '')
   .replace(/\)/g, '')

How to read and write file using fs in node

Issue #419

function write(json) {
    const data = JSON.stringify(json)
    const year = json.date.getFullYear()
    const directory = `collected/${slugify(className)}/${year}`

    fs.mkdirSync(directory, { recursive: true })
    fs.writeFileSync( …

How to get videos from vimeo in node

Issue #418

Code

Path for user users/nsspain/videos Path for showcase https://developer.vimeo.com/api/reference/albums#get_album Path for Channels, Groups and Portfolios

const Vimeo = require('vimeo').Vimeo
const vimeoClient = new Vimeo( …

How to get videos from youtube in node

Issue #417

class Youtube {
    async getVideos(playlistId, pageToken) {
        const options = {
            key: clientKey,
            part: 'id,contentDetails,snippet',
            playlistId: playlistId,
            maxResult: 100, …

How to convert callback to Promise in Javascript

Issue #416

// @flow

const toPromise = (f: (any) => void) => {
  return new Promise<any>((resolve, reject) => {
    try {
      f((result) => {
        resolve(result)
      })
    } catch (e) {
      reject(e)
    }
  })
}
const …

How to fix electron issues

Issue #415

Electron require() is not defined

https://stackoverflow.com/questions/44391448/electron-require-is-not-defined

function createWindow () {
  win = new BrowserWindow({
    title: 'MyApp',
    width: 600, 
    height: 500, …

How to make simple traffic simulation in Javascript

Issue #400

How to make collaborative drawing canvas with socketio and node

Issue #399

Client

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Main from './Main'

class App extends …

How to generate changelog for GitHub releases with rxjs and node

Issue #398

How to

Technical

Dependencies

const Rx = require('rxjs/Rx')
const Fetch = require('node-fetch') …

How to get all GitHub issues using GraphQL

Issue #393

https://developer.github.com/v4/explorer/

query { 
  repository(owner: "onmyway133", name: "blog") { 
    issues(orderBy: {field: UPDATED_AT, direction: ASC}, last: 100) {
      edges {
        cursor
        node { …

How to use Hexo to deploy static site

Issue #392

It’s been a long journey since https://github.com/onmyway133/blog/issues/1, next step is to keep GitHub issues as source, and mirror those to a static site.

Use 2 repos

How to use type coersion in Javascript

Issue #391

People who make fun of Javascript probably don’t understand implicit type coersion and when to use triple equal. Javascript is very unexpected, but when we work with this language, we need to be aware.

  1. Coercion–Automatically …

How to safely access deeply nested object in Javascript

Issue #390

An object ’s property can be null or undefined.

Accessing step by step is tedious

props.user &&
props.user.posts &&
props.user.posts[0] &&
props.user.posts[0].comments

Dynamic parsing path is too clever and …

How to use flow type in Javascript

Issue #389

Prefer flow over TypeScript for simplicity

Javascript primitive types number and string are too general and do not express the domain objects. Because lack of type alias in Javascript, we can use flow

export type Centimeter = number
export …

How to use React JSX with Babel in Electron

Issue #352

For a normal electron app created with npm init, we can use all features of ES6, but not the JSX syntax for React. We can use just Babel to transpile JSX, as used in IconGenerator

.babelrc

{
  "plugins": [ …

How to submit electron app to AppStore

Issue #342

Before

Install electron as dev npm install electron --save-dev Update electron-packager npm install electron-packager@latest --save-dev Use no space in app name

Package with electron-packager

Follow …

How to organise test files

Issue #327

In terms of tests, we usually have files for unit test, UI test, integeration test and mock.

Out of sight, out of mind.

Unit tests are for checking specific functions and classes, it’s more convenient to browse them side by side …

What is create-react-native-app

Issue #279

Original post https://medium.com/fantageek/what-is-create-react-native-app-9f3bc5a6c2a3


As someone who comes to React Native from iOS and Android background, I like React and Javascript as much as I like Swift and Kotlin. React Native is …

How to make tag selection view in React Native

Issue #271

Original post https://hackernoon.com/how-to-make-tag-selection-view-in-react-native-b6f8b0adc891


Besides React style programming, Yoga is another cool feature of React Native. It is a cross-platform layout engine which implements Flexbox …

Getting to know some pragmatic programming language features

Issue #270

As you know, in the Pragmatic Programmer, section Your Knowledge Portfolio, it is said that

Learn at least one new language every year. Different languages solve the same problems in different ways. By learning several different …

How to add app icons and splash screens to a React Native app in staging and production

Issue #268

React Native was designed to be “learn once, write anywhere,” and it is usually used to build cross platform apps for iOS and Android. And for each app that we build, there are times we need to reuse the same code, build and tweak it a bit …

Get to know different JavaScript environments in React Native

Issue #266

Original post https://medium.freecodecamp.org/get-to-know-different-javascript-environments-in-react-native-4951c15d61f5


React Native can be very easy to get started with, and then at some point problems occur and we need to dive deep …

How to Make Linear Gradient View with Bridging in React Native

Issue #264

Original post https://medium.com/react-native-training/react-native-bridging-how-to-make-linear-gradient-view-83c3805373b7


React Native lets us build mobile apps using only Javascript. It works by providing a common interface that talks …

How to dismiss keyboard with react-navigation in React Native apps

Issue #263

Original post https://medium.com/react-native-training/how-to-dismiss-keyboard-with-react-navigation-in-react-native-apps-4b987bbfdc48


Showing and dismiss keyboard seems like a trivial thing to do in mobile apps, but it can be tricky in …

How to structure your project and manage static resources in React Native

Issue #256

Original post https://medium.freecodecamp.org/how-to-structure-your-project-and-manage-static-resources-in-react-native-6f4cfc947d92


React and React Native are just frameworks, and they do not dictate how we should structure our projects. …

How to overlay view on another view in React Native

Issue #254

Original post https://stackoverflow.com/a/54108708/1418457


Make our own convenient OverlayContainer. The trick is to use absolute with 100% size

// @flow

import React from 'react'
import { View, StyleSheet } from …

How to remove Cartography in iOS

Issue #252

Read more https://medium.com/flawless-app-stories/how-to-make-auto-layout-more-convenient-in-ios-df3b42fed37f

Description

This is a script to remove Cartography, and use plain NSLayoutAnchor syntax. Use Constraint.on() from Sugar. It will …

How to sort strings with number in Javascript

Issue #251

function sort() {
    const string = 
`
- Favorite WWDC 2017 sessions https://github.com/onmyway133/blog/issues/56
- Favorite WWDC 2018 sessions https://github.com/onmyway133/blog/issues/245
- How to do clustering with Google Maps in iOS …

How to catch error in ApolloClient

Issue #192

Read https://www.apollographql.com/docs/react/features/error-handling How to catch actual error https://github.com/apollographql/apollo-client/issues/4016 🤔

import { Observable } from 'apollo-link'
import ApolloClient from …

Curry in Swift and Javascript

Issue #185

You may encounter curry in everyday code without knowing it. Here is a bit of my reflections on curry and how to apply it in Javascript and Swift.

Taking one parameter in Haskell

In Haskell, all function officially takes only 1 parameter. …

How to get properties of JSValue in JavascriptCore

Issue #179

let rough = context.objectForKeyedSubscript("myObject")
myObject.toDictionary()

Learning flexbox

Issue #62

CSS

Flexbox