Skip to content

Instantly share code, notes, and snippets.

View librz's full-sized avatar

Patrick Ren librz

View GitHub Profile
@librz
librz / native-fetch-wrapper.ts
Last active March 10, 2023 05:45
An exmaple of a wrapper on top of browser's native fetch method
/**
* example of a wrapper of browser's native fetch method
* Assumptions:
* 1. server uses JWT & bearer token for authorization
* 2. client stores auth token in local storage
* 3. response's content type
* a. "application/json" for normal response
* b. "application/octet-stream" for file download
* c. "text/plain" when error
* 4. server returns 401 when auth token is invalid
@librz
librz / setstate-is-async.tsx
Created December 29, 2022 10:12
Proof React's setState is asynchronous
import { useState, FC } from "react";
const App: FC = () => {
const [number, setNumber] = useState(1);
const nextNumber = number + 1;
function handleIncrease() {
setNumber((num) => num + 1);
console.log("current number is", number); // still the old number
@librz
librz / render-props.tsx
Last active December 14, 2022 04:37
Render props pattern in react
// ref: https://www.patterns.dev/posts/render-props-pattern/
// note: in many cases, render props can be replaced by hooks
import { FC, useState } from "react";
interface IContainerProps {
children: (bg: "silver" | "gold") => React.ReactNode;
}
const Container: FC<IContainerProps> = ({ children }) => {
@librz
librz / pubsub.ts
Last active December 4, 2022 01:28
naive example code for "topic based publish/subscribe model"
// naive example code for "topic based publish/subscribe model"
// this is just to illustrate the idea, feature is incomplete, do NOT use in production
// reference: https://github.com/mroderick/PubSubJS
type TopicHandler = (data?: any) => void;
interface ISubscriber {
topic: string;
handler: TopicHandler
}
@librz
librz / use-context.tsx
Last active February 2, 2023 09:39
Example of using context in react
/* define context */
import React, { createContext } from 'react'
// the biggest limitation of context is there's no way of refering to & setting state when defining context
// actions can only be implemented inside context provider
const LayoutContext = createContext<{
collapsed: boolean,
toggleCollapsed: () => void
}>({
@librz
librz / analyse_tags.js
Last active December 4, 2022 03:47
Analyze HTML tags of current page
const allSelectors = document.querySelectorAll("*");
console.log(`In this page, there are ${allSelectors.length} HTML tags.`)
const selectorToCount = {};
allSelectors.forEach(it => {
if (!(it.tagName in selectorToCount)) {
selectorToCount[it.tagName] = 1;
} else {