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 state and lifecycle of API requests, and by combining it with debouncing, you can create a powerful and efficient data fetching solution. In this tutorial, we’ll walk through an example of using useQuery with debouncing to fetch country details based on user input in an autocomplete component....

August 14, 2024 · 4 min · 727 words · Khoa

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 with pnpm and webpack. In our example, the domain we want to use is local.onmyway133.com Map Localhost to Your Domain Name First, we need to map our custom domain to localhost. Open your hosts file to add this mapping....

July 29, 2024 · 2 min · 316 words · Khoa

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 global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace NodeJS { interface ProcessEnv { NODE_ENV: 'test' | 'dev' | 'prod' } } } type Data = Record<string, unknown> const defaultData: Data = {} const adapter: SyncAdapter<Data> = process.env.NODE_ENV === 'test' ? new MemorySync<Data>() : new JSONFileSync<Data>('db.json') const db = new LowSync<Data>(adapter, defaultData) db....

July 11, 2024 · 1 min · 75 words · Khoa

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 standardized way. Boom provides a set of functions to generate HTTP error objects with consistent properties, making it easier to handle errors and communicate them to clients Read Error transformation...

January 31, 2024 · 1 min · 114 words · Khoa

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 other type, gets created in memory when the code within a function’s scope is executed. This poses a challenge for React’s rendering logic, which determines the need for re-rendering based on changes in input props and context....

January 26, 2024 · 2 min · 398 words · Khoa

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 object-oriented programming languages like Java or C#. Extending classes is also a feature of ES6, which allows you to create a new class from an existing class. This is done through the extends keyword....

January 25, 2024 · 4 min · 689 words · Khoa

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 export * syntax is used to re-export all exportable members from the imported module. It’s a way to aggregate exports from several modules into a single module. For example, let’s say we have a couple of modules, each exporting some components:...

January 25, 2024 · 2 min · 397 words · Khoa

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 = useCallback( debounce((value: string) => { props.setFilter({ ...props.filter, searchText: value, }) }), [] ) const handleChange = (value: string) => { callback(value) } return ( <div> <Input value={props.filter.searchText} placeholder="Search" variant="bordered" onValueChange={handleChange} /> </div> ) }

November 19, 2023 · 1 min · 67 words · Khoa

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: string } removeDuplicates = (array: Deal[]) => { const map = new Map() array.forEach((item) => map.set(item.link, item)) return [...map.values()] } We might need to update tsconfig.json...

November 17, 2023 · 1 min · 77 words · Khoa

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" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) }

November 4, 2023 · 1 min · 47 words · Khoa

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 import { NextResponse, NextRequest } from "next/server" const Middleware = (req: NextRequest) => { if (req.nextUrl.pathname === req.nextUrl.pathname.toLowerCase()) { return NextResponse.next() } return NextResponse.redirect( new URL(req.nextUrl.origin + req.nextUrl.pathname.toLowerCase()) ) } export default Middleware

July 17, 2023 · 1 min · 72 words · Khoa

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 "react-syntax-highlighter" import { oneDark } from "react-syntax-highlighter/dist/cjs/styles/prism" import rehypeRaw from "rehype-raw" type Props = { content: string } export default (props: Props) => { return ( <div className="markdown-body"> <ReactMarkdown children={props.content} rehypePlugins={[rehypeRaw]} components={{ code({ node, inline, className, children, ...props }) { const match = /language-(\w+)/....

June 6, 2023 · 1 min · 104 words · Khoa

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" } Then in landing/package.json, use file { "name": "landing", "version": "0.1.0", "private": true, "homepage": ".", "dependencies": { "@emotion/core": "^10.0.28", "react": "^16.13.1", "react-dom": "^16.13.1", "react-image": "^2.4.0", "react-scripts": "3.4.1", "data": "file:../data" },

January 17, 2021 · 1 min · 51 words · Khoa

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 European Standard Time)" date.toISOString() // "2020-12-05T05:58:19.081Z" We can use toISOString, then split base on the dot . then remove character T date .toISOString() .split('.')[0] .replace('T', ' ')

December 5, 2020 · 1 min · 69 words · Khoa

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 ( <ZStack> <Header /> <div css={css` padding-top: 50px; `}> <Showcase factory={factory} /> <Footer /> </div> </ZStack> ) } } /** @jsx jsx */ import React from 'react'; import { css, jsx } from '@emotion/core' export default function ZStack(props) { return ( <div css={css` position: relative; border: 1px solid red; `}> <div css={css` position: absolute; top: 0; left: 0; width: 100%; z-index: -1; `}> {props....

November 18, 2020 · 1 min · 110 words · Khoa

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.log(error) } } listenChats() }, [year, id]) } Hooks effect https://reactjs.org/docs/hooks-effect.html https://reactjs.org/docs/hooks-reference.html#useeffect By default, it runs both after the first render and after every update. This requirement is common enough that it is built into the useEffect Hook API....

June 17, 2020 · 1 min · 126 words · Khoa

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 to import from moment-timezone, not moment import moment from 'moment-timezone' moment(startAt).tz('America/Los_Angeles').format('MMMM Do YYYY')

June 13, 2020 · 1 min · 28 words · Khoa

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 (e.key === 'Enter') { onSend(e) } }} />

June 12, 2020 · 1 min · 29 words · Khoa

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 (e.key === 'Enter') { onSend(e) } }} /> Updated at 2020-06-16 07:30:52

June 12, 2020 · 1 min · 33 words · Khoa

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 } from 'react-router-dom' function _ScrollToTop(props) { const { pathname } = useLocation(); useEffect(() => { window.scrollTo(0, 0); }, [pathname]); return props.children } const ScrollToTop = withRouter(_ScrollToTop) function App() { return ( <div> <Router> <ScrollToTop> <Header /> <Content /> <Footer /> </ScrollToTop> </Router> </div> ) } Updated at 2020-06-04 05:58:47

June 4, 2020 · 1 min · 71 words · Khoa